DEV Community

Jack Chen
Jack Chen

Posted on

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?

Top comments (3)

Collapse
 
crimsonmed profile image
Médéric Burlet

Iv'e been using overmindJS for a while now and really love it~
It evens comes with a graphql version.

GitHub logo cerebral / overmind

Overmind - Frictionless state management

Overmind

Visit website for more information: overmindjs.org.

Release procedure

$ git checkout next
$ git pull
$ npm install # make sure any new dependencies are installed
$ npm install --no-save nodegit  # needed for "repo-cooker --release"
$ npm run release -- --dry-run --print-release  # and check release notes
$ git checkout master
$ git pull
$ git merge --ff-only next
$ git push
Enter fullscreen mode Exit fullscreen mode

VSCode extension is released via .travis.yml due to limitations of the publishing tool that is unable to use root node_modules folder




Collapse
 
chenchengxing profile image
Jack Chen

It looks like redux~

Collapse
 
crimsonmed profile image
Médéric Burlet

Simpler to setup and use imo