Normal
Normal

Reputation: 3716

Shall we globalize all the states of a react application?

I have a question regarding the state management when using redux. the main aim of Redux is to globalize the state of the components so every component in the App can read and update that state.

My question is: When we write React/Redux applications, which design pattern we should use? to define every state in the Redux store? or to only define the states that require to be read by other components in the Redux store, and the rest will be encapsulated inside their relative components?

I think you got my question right? :D

Now, how about components' reusability? doesn't redux make it impossible for the components to be reusable?

& Thank yous 😘

Upvotes: 1

Views: 58

Answers (1)

A G
A G

Reputation: 22587

There is no “right” answer for this. There are some Recommendations though -

Some common rules of thumb for determining what kind of data should be put into Redux:

  • Do other parts of the application care about this data?
  • Do you need to be able to create further derived data based on this original data?
  • Is the same data being used to drive multiple components?
  • Is there value to you in being able to restore this state to a given point - in time (ie, time travel debugging)?
  • Do you want to cache the data (ie, use what's in state if it's already - there instead of re-requesting it)?
  • Do you want to keep this data consistent while hot-reloading UI components (which may lose their internal state when swapped)?

From Redux Github - Question: How to choose between Redux's store and React's state? #1287

dan_abramov - Use React for ephemeral state that doesn't matter to the app globally and doesn't mutate in complex ways. For example, a toggle in some UI element, a form input state. Use Redux for state that matters globally or is mutated in complex ways. For example, cached users, or a post draft.

Sometimes you'll want to move from Redux state to React state (when storing something in Redux gets awkward) or the other way around (when more components need to have access to some state that used to be local).

The rule of thumb is: do whatever is less awkward.

Cheatsheet -

enter image description here

Upvotes: 1

Related Questions