Almost every application you write contains state and you'll need some way to manage it, but how?
3 min read
·
By Marianne Grov
·
December 4, 2018
Redux is often used for state management in React apps, but it is possible to manage state within React itself. So, what is the best solution for your application? It depends. Let's take a look at some characteristics that can make the choice clearer.
In the article 'You Might Not Need Redux', Dan Abramov states that not all applications need Redux for state management. I recommend reading for more insight on this topic. Even though your app needs Redux to handle state, there is nothing wrong in using local state in some parts of your application.
Some state is used widely and needs to be persisted over time, while other state needs to be stored shortly and is used at one place only. Whilst the first one might benefit from Redux or even needs more persistent storage, the second case is much simpler and can suffice with the simpler React State.
The following two questions can be helpful in making a decision.
Data that only needs to be stored for a short time is well suited for using local React state. Examples are the content of an input field, a form that is not yet submitted, or how to filter a list of items.
If the state is needed as the user navigates across the application, and it is expected to be present until next refresh, local state is not recommended.
Is your state isolated? If your state is used at a small part of your application, or in a specific component, local state is a good solution.
If several unrelated components need the same data, it is better to put it in the Redux store. The same goes if the data is used by multiple subcomponents. In this case there will be a large amount of overhead in sending the required props down to all child components.
One big advantage with Redux is the possibility to track changes of state and play the changes step by step. This is useful when debugging complex state, but is not necessary for the parts of your state that are simple and isolated.
Local state is a good solution if the state is isolated and needs to be persisted shortly. Redux offers great state management, but also adds overhead which can be avoided if local state is used instead. The most important thing to remember is that one doesn't rule out the other.