Home > Software design >  When I store data in Redux and when not?
When I store data in Redux and when not?

Time:11-19

I'm working with a react app and currently working with a feature. The main task is showing some charts by getting data from API. And these charts will show the last 30 minutes' data.

I have questions,

  1. In this situation, is it necessary to store these data in the state by Redux, though it can be handled at components very easily? And every time I refresh or request, I get new data (log base data).
  2. When do we make the mind to store data in state and when not?

CodePudding user response:

A redux store is a singleton, thus a single source of truth that can be made available to all components in the whole react application. If your state is intended only for one react component then you don't need a redux store. A useReducer react hook allows to well reproduce the redux pattern in a single component. Stick with a useReducer hook for a single component and use redux library for a store available to an app composed of several components.

CodePudding user response:

If data is being used for many states or those data are being used by many components then you should use redux. You can still go without redux if that data is not complex and not used on different routes.

If you have various components and routes then redux will help you to reduce the codes and also make the codes simpler. Redux will give the one store for all the components in the project to store and access the data which is better then context or props tricks.

Also if you want to achive something like if user opened two different tabs. Let it be same page or two different pages of your website and if user done an action on page A and you want that page A or page B opened in another tab should get that update then redux can let you achive that. Context and props passing are not useful in this case.

https://redux.js.org/faq/general#when-should-i-use-redux

Redux is most useful when in cases when:

  1. You have large amounts of application state that are needed in many places in the app
  2. The app state is updated frequently
  3. The logic to update that state may be complex
  4. The app has a medium or large-sized codebase, and might be worked on by many people
  5. You need to see how that state is being updated over time

CodePudding user response:

Redux is not designed for the specif role of a special type of data. You can use still store your temporary (30 min) data into redux, and use it to cross your feeling the same as the rest of your data.

But in this case, you might need to reset data after 30 minutes or invalidate your cache, keep your eye in react-query and RTK-query handling these types of actions more easily for you.

  • Related