-
Notifications
You must be signed in to change notification settings - Fork 0
State Management Comparison
- simplest way to manage state
- always start with until you find yourself "drilling props" through components
- Simple applications can manage with local state
- Once you have components who's job is simply to pass a prop to another, you could likely benefit from an alternative state management solution
-
Authentication, Languages, Theme providing
-
When you need to pass state to multiple different components, and find yourself "prop drilling" to solve this need
-
Benefits/Problems it solves
- Solves the problem of passing props through many levels of components when intermediate components don't use said props
- As of React 16.3, Context is production supported
- Allow for separation of state into different contexts
-
Pain Points
- makes component re-use difficult
- isn't always the right solution
- Complex contexts will cause consumers to re-render even when a field gets updated that they do not care about
-
Alternative
- You can pass down whole component rather than individual props to avoid re-rendering of intermediate components that don't use prop
- Event driven state change
- Asynchronus state changes
- Makes it easier to change the structure of your state
- Redux allows you to isolate state away from your components
- Provider is redux is always your higher order component
- Context you still have to worry about the order of your Provider/Consumer components
- Only re-renders components listening to the parts of state that get changed
-
Can logically separate stores and keep denormalized data
-
Data is stored via observable, can automatically track changes to data by listening to observable instead of tracking manually
-
States are mutable, can be overwritten (also possible source of pain)
-
When to use Redux/State Management tools:
-
When you want event-driven stage change, calls with asynchronous behavior, redux helps you see and control the order in which state changes can apply.
-
When you have no idea what your end state looks like. Makes you more flexible to change.
-
If you have a clear idea of how your app is going to look, local state should be fine.
-
Without a state management tool, if state is shared by far away components, the state will have to be lifted up to the nearest parent component and to the next until it gets to an ancestor that is common to both components that need the state and then it is passed down.
-
Now with context and hooks, state management tools aren’t as needed. It’s just on you to enforce immutable state change.
-
Redux always have one large store in which all the states are stored. MobX typically has more than one store. As a result in MobX you can logically separate your stores.
-
Also, in Redux the data is usually normalised. In MobX, you can keep an denormalised data.
-
General consensus seems to be:
- Less complex -> go with MobX
- More complex -> go with Redux