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.

Use Redux if you’d like to keep the state across the page refreshes. Use setState() if it isn’t necessary

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 pageThe open/closed state of a dropdown
The current page of a book in a book reader appThe visibility of toolbars in the app
The current level in Angry BirdsThe 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

Mar 18   react   redux
Erik Harper

If your app is built from a single root component, then you could still have global state across components using setState.

Ivan Akulov

Yes. However, you’d have to pass it down to every component either through props (which means a lot of boilerplate code if the components are deep) or through context (which is unstable). People I’ve talked with prefer Redux in this case.

Erik Harper

Correct, but in Redux you have containers, which hold state from Redux, but that state is usually passed down to child components as props anyway. I think what differentiates Redux from setState is it allows you to create multiple components that connect to a slice of the global state, but at the end of the day, state is still passed as props down the tree in both cases in the exact same way. The only other difference Redux has from setState is the state is stored in a separate object instead of a React component.

“Redux = data grabbing and global state that’s shared across more than one component.”

What this quote above should instead say is “Redux = data grabbing and global state that’s shared across more than one top-level component.”

Your comment
won’t be published

HTML will not work

Ctrl + Enter