Redux vs React’s setState()
Sometimes you can get into a situation when you’re choosing between Redux and React’s setState(). When I’m doing such choice, I like to use the following criterion.
Imagine that the browser keeps the stuff you store in Redux even when you refresh the page.
Basically, this is about the importance of a piece of state. Is it important enough to put it into the store and 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:
|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.
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.
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.
I’m writing a practical introduction into webpack in three parts, and I’m publishing the second part soon. Subscribe