Sometimes you can get into a situation when you’re choosing between Redux and React’s setState(). When I’m doing such choice, I often use the following rule of thumb.
Imagine that your app can restore its state when you refresh the page.
Use setState() if don’t have this need
Basically, this is about the importance of a piece of state. Is it important enough to keep it across refreshes? If yes, use Redux. If no, setState() would do the job just fine.
Here’s how I’d make the choise:
Redux | setState() |
---|---|
The selected value in a dropdown on a page | The open/closed state of a dropdown |
The current page of a book in a book reader app | The visibility of toolbars in the app |
The current level in Angry Birds | The state of birds and pigs in the current level in Angry Birds |
For me, the state in the left column is important, and the state in the right column is not. Your app can require a different decision.
This criterion is not universal – i.e. sometimes you might need to put the “dropdown is open” state into the store because you change another component’s styles based on this. But for me, it works in most cases.
Posting this on Reddit triggered a great comment:
Redux = data grabbing and global state that’s shared across more than one component.
setState = silo’ed state that is isolated from other components.
– jiblet84
Yes! Another (and probably more common, as I’m realizing after receiving the feedback) criterion for choosing between Redux and setState() is how global the state is. So here’s another approach:
Use Redux if your state is shared across multiple components. Use setState() if it’s used only in a single component.