When to put data in Redux

Eleni Chappen
20spokes Whiteboard
2 min readApr 9, 2018

Lots of internet ink has been spilled over when to keep data in an application state management system (like Redux) versus in a React component’s internal state. While I have mentioned benefits to Redux before, it’s important to understand the tradeoffs.

Keeping state in components has pros and cons:

Pro: your data is cleared when the component unmounts!
Con: your data is cleared when the component unmounts.

Likewise, keeping data in app state has pros and cons:

Pro: your data persists between components!
Con: your data persists between components.

Personally, I err on the side of keeping data out of app state. If I’m creating a new component and I’m unsure where to store my data, I’ll use internal state, then port to Redux when it becomes necessary.

It’s helpful to conceive of your app state as a collection of global variables. Normally, global variables are to be avoided. You wouldn’t add global variables willy-nilly in a Rails or Python app. Have the same precaution when adding globals client-side.

Like any other global variable, when you make the decision to move your data into the global app state, it is now up to you to manage it. For instance, you’ll probably need to clear your app state when a user logs out. When a user exits a multi-step form, you may need to clear any data that user entered.

Constructing your container components thoughtfully can help you avoid manually managing state like this. With multi-step forms, I typically create a wrapper component that’s responsible for rendering each step of the form, keeping all user-entered data in its own state. From this container, I can pass any of its state and functionality down to each step as props. It’s a simple solution, but an often overlooked one, especially when Redux is already in your app and you see other components using it.

When an app uses Redux, it’s impossible to prevent future maintainers from simply adding everything to app state. You can mitigate this by stressing in your documentation how keeping state in Redux can be dangerous. You can also practice predictable state patterns in your own components (like the form wrapper), setting good examples for future developers. But ultimately it’s a hard thing to enforce, and this should be considered when deciding to add Redux to your application.

--

--