React, why we need state management and how we can do it well

chenchengxing

Jack Chen

Posted on November 8, 2020

React, why we need state management and how we can do it well

State management seems like a fancy word. But however you put it, we need to manage it or deal with it in some ways.

Think in this way: the application is like a state-machine which goes from one state to another. And that means we can have lots of states in our app which can be decided or derived from variables or values.

The way we're handling all these variables or values is called state management.

Common State Levels through out

State in Component level

In old times, we can use state setState() to get hold of and change state.

With the help of hooks, simply [state, setState] = useState() will do

State in Page level

Similar to state in component, you can treat it as a Page Compenent.

Things to note here is that at some point you have to use it and maybe you have to pass it to the child component which can be really deep.

State in Application level

Believe me, we have those things like Global Snackbar or Global Banner which are those things that only have one instance or have only one state to represent it in the whole application.

We can of course manage it in the root component and pass it down deep, but don't..

How to deal with it or manage it

State in Component level

Just use hooks, it's easy and effective.

State in Page and Application level

Use React.Context or third party Mobx or Redux to manage it.

My Recommendation

There's no holy grails here. You can choose to do it in any way. But to me, it's very easy and straightfoward to go with the Mobx way.

With the Mobx way, you can easily define the state you want. No hierachy needed. The state doesn't have to be tied to a root. They can be managed as individuals just as they might be.

The idea is very much like it's in Recoil.
react_recoil_-_Google_Search

It's also amazing to get hold of the state and update with the help of useContext.

No more redux boilerplates, no more Providers, so why not?

💖 💪 🙅 🚩
chenchengxing
Jack Chen

Posted on November 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related