DEV Community

Cover image for Do you need a State Management Library?
Andrew Bone
Andrew Bone

Posted on

Do you need a State Management Library?

The other day I was browsing LinkedIn when a poll caught my eye

What's your favourite React State Management Library and why?

LinkedIn poll

Naturally, I felt there was an option missing from the poll and left a comment. I replied saying I felt a custom hook with the context API should be enough, let's talk about that.

What is a State Management Library?

Before we look at what state management is we have to agree on what state is. State is a place in memory where we can store some data, anything really. For instance with a checkbox it is either checked or not, true or false, and they are its states, storing a user's name as a string is a state or an array of preferences, the list is endless.

So what is state management? These states/variables need to be interacted with some how. Be it reading the value or setting it. In it's most simple form state management is how you interact with a variable.

In React, states are easy provided you only want to touch them inside the components they were made in. State Management Library's, for React, make it possible to interact with states from anywhere without having to prop drill. This is great and it why these libraries are so popular but is there a better way?

What is the context API?

The context API is a default React hook used to allow data (objects, functions, strings, etc) to be accessed by any child component.

When we use this API in tandem with a custom hook it gets a lot more powerful. We can pass objects with getter and setter functions that can be used read or modify states, as you'd expect, or have functions that allow us to set several states at once or even give us data back in certain formats, perhaps for API calls.

How can we use the context API?

Here I've written a very simple hook to manage storing a person's name. It stores a first and last name, which you can both get and set, it also concatenates the two names into one long name that can be read from context, this is not something you'd ever really need to do but it shows how data can be returned formatted, there is also a function that lets you set both states at once.

Have a look through the code, as I said it's nothing complex but it was only meant to serve as an example of what can be done rather than a template to be followed.

Final thoughts

With all of this power built into React do we need State Management Libraries? Maybe we do or maybe we don't but either way please let me know if you use one and if you do why? I look forward to reading your comments.

Thank you so much for reading.

Oldest comments (58)

Collapse
 
rowlinsonmike profile image
Michael Rowlinson

Zustand is simple to learn and powerful. Easy manipulation inside and out of components. Very little boilerplate. Many performance optimizations baked in.

Collapse
 
link2twenty profile image
Andrew Bone

I've never heard of Zustand, what would you say its main benefits are?

Collapse
 
rowlinsonmike profile image
Michael Rowlinson

From my experience, I like that it is dead simple. Recoil is close but still requires Context providers. I like that state is easily manipulated outside of components as well. There are many complex use cases in the docs implemented in very clever intuitive ways, like its use of immer for reductions and transient updates.

Thread Thread
 
jerevick83 profile image
jerevick83

How do you work around it's persistency? I tried using it to persist basic user data but that became messier as there was lots of persisted data in the localstorage for even signed out users. I mean lots and lots of them.

How do I persist and clear the entire storage after signing out?

Collapse
 
krtirtho profile image
Kingkor Roy Tirtho

If you're using react-query/react-swr for data fetching/caching then Context API will be enough for managing the simple UI states

Collapse
 
ivan_jrmc profile image
Ivan Jeremic • Edited

I use also react-query and also sometimes context for UI state but mostly recoil, what are you doing in context to avoid rerenders or do you simply don't care if components rerender?

Collapse
 
link2twenty profile image
Andrew Bone

What are you doing in context to avoid rerenders?

Good question, it is my understanding that a component will only rerender if the context in question is loaded in using useContext. Because of this I find it best to have several contexts for different types of data and only add the contexts where they are relevant.

For instance I may have a user data context that gets data from the server but then I may also have a permissions context that gets different data from the server but won't need to update if the user updates their profile picture.

By keeping contexts separate, and using them sparingly, you can prevent excessive redraws.

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic • Edited

Yes that is one way creating multiple contexts and making sure each context keeps only one piece of state never more than one, to avoid a bunch of code and boilerplate I recommend you to look at recoil it is just react under the hood no external deps. It does the same but without you need to take care how and where to inject the context

Collapse
 
krtirtho profile image
Kingkor Roy Tirtho

I use zustand in this case. It's the most efficient in this case

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic • Edited

Hard to use zustand when the creator of it himself says Jotai is better. They are both from the same team and Jotai is inspired by recoil.

Thread Thread
 
krtirtho profile image
Kingkor Roy Tirtho

What? When? I never saw him writing such thing. Not even on the README. BTW, zustand has double stars in Github compared to jotai

Also, zustand has over 113k downloads per week in npmjs.com where jotai is only has 5-7k downloads per week

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic

It was a tweet.

Collapse
 
link2twenty profile image
Andrew Bone

I tend to use vanilla fetch for my queries rather than a hook, though I do sometimes make a hook like my example one to handle the initial fetch and refreshes. Are there any advantages to using react query other than it makes initial setup time quicker?

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

Yes manny, mostly boilerplate you need to much boilerplate if you do everything yourself, I know it is not hard but it simply is more code.

Collapse
 
hoandt profile image
hoandt

useContext and probably UseQuery from react-query are what I need.

Collapse
 
link2twenty profile image
Andrew Bone

What is it you like about useQuery? I tend to write my own fetch requests, even though that can lead to code repetition.

Collapse
 
hoandt profile image
hoandt

UseQuery caches fetched data. I would create a custom hook to handle the cache. Like useContext, you can get that cache globally.

It’s very handy to me when I apply it to store logged in user details.

Collapse
 
thevediwho profile image
Vaibhav Dwivedi

Here's an interesting fact I wanted to share after reading this. When I started learning React in 2017, I built a big project for a client in React.

What's crazy is that I didn't use state management at all in it. But now that I look back at it, I feel like it could've been made much better with it. Anyhow, great read.

Collapse
 
link2twenty profile image
Andrew Bone

That is interesting. I try to use a few states as possible myself though, of course, still use a few.

For instance it's common to see a snippet like

  const [input, setInput] = useState();

  const displayValue = () => {
    console.log(input);
  }

  return (
    <>
      <input value={input} onChange={({target}) => setInput(target.value)} />
      <button onClick={displayValue}>Display</button>
    </>
  )
Enter fullscreen mode Exit fullscreen mode

Which takes the state away from the input and stores it in React. The only problem with this is it now takes process time, even though it's only a small amount, between each key stroke.

I'm much more likely to do something like

  const input = useRef(null);

  const displayValue = () => {
    const { current: el } = input;
    console.log(el.value);
  }

  return (
    <>
      <input ref={input} />
      <button onClick={displayValue}>Display</button>
    </>
  )
Enter fullscreen mode Exit fullscreen mode

This has the exact same outcome but will only need process time when the button is pressed rather than on every key stroke.

Collapse
 
bennodev19 profile image
BennoDev

I prefer to use AgileTs,
as it allows the easy creation of individual and independent States, which (in my opinion) are more straightforward and performant to handle. These States are even accessible outside the React Tree, which allows me to decouple my business logic from the UI.

Also, it has some nice add-ons like a Form-Manager, Event-Handler, ..

Example

Collapse
 
link2twenty profile image
Andrew Bone

Great question 😊

useState is great but is component specific. You can share the state with props and even share functions to modify the state in the same way but as your app gets bigger this can become complex.

Say you have an shopping app that lets you add items to your cart before you buy them. Each product pages needs to know if they're in the cart and if they are how many are, the checkout page needs to know the cart contents and the app bar needs to know how many items are in the cart to display a number.

You could store the cart state at top level and pass functions and states to relevant children via props or you could handle it using a context. This makes the code easier to understand and, generally, run faster.

Does that make sense?

Collapse
 
sgoulas profile image
sgoulas • Edited

Context API is not a state management tool, neither it provides the benefits of one. It also forces rerenders across your application, degrading its performance. It should be used only for specific variables that you know beforehand they are not going to change often.

Collapse
 
link2twenty profile image
Andrew Bone

Which benefits are missing? Rerenders only happen for components that use the specific context that has a change. I generally have a different context for each dataset but try to have as few contexts as possible, this keeps rerenders to a minimum.

Collapse
 
sgoulas profile image
sgoulas • Edited

A state management solution stores a value itself. Context does not store a value, it merely provides a point of access for said value. The parent component that provides the context to the children is the one responsible for "storing" the value. Context also does not provide any mechanism for handling side effects. If you want to handle a login authentication flow with classic state management tools you have thunks, observables, sagas etc. Context does not handle side effects. Context also does not offer time travelling debugging. At any given point you can not deterministitcally know how the value passed by context came to be, whereas with state management tools you can inspect the sequence of dispatched actions.

Also, on the topic of multiple contexts, I can't speak without checking an actual example (the one provided in the post uses a single context provider), but the moment the application becomes a little bigger, sustaining a large number of different contexts becomes an impossible task. You have to juggle between what provider wraps what part of the component tree and then be specific in how you consume the provided value in that part of the tree. The moment you want a component to access a context value that was not previously available to it you have to restructure your provider wrappers to accomodate for this change. And this brings me to my final point, application wide state management solutions mean that all the reducers listen to all the dispatched actions, they just don't match actions for which they don't have a corresponding case. This means that at any given point a component connected to the redux store can dispatch an existing action and trigger a change in the application wide state. You can't do that with context because you have to be constantly aware of the whole structure so that a component can be inside the specific wrapper tree it needs to be. And of course, just as I mentioned earlier, even then, the value is not stored in the store, it's stored in a parent component.

You can also read a post by acemarke, a redux maintainer and one of the creators behind redux toolkit explaining in much greater detail why context is not a substiture for redux, their differences and their respective use cases:

blog.isquaredsoftware.com/2021/01/...

Thread Thread
 
link2twenty profile image
Andrew Bone

Yes, I know context isn't a state management solution hence saying

When we use this API in tandem with a custom hook it gets a lot more powerful.

But I don't really know what more you need other than global state. There are different ways to interact with state, like dispatching, but any of these can be coded into your hook and a just syntax sugar.

As for them getting to complex and hard to manage, this isn't a problem I've faced so far but one I understand.

Thank you for linking the blog post I'll give it a read 😀

Collapse
 
ash_grover profile image
Ash G

Rerenders only happen for components that use the specific context that has a change.

Careful here. If you're maintaining a global context, any change in any of the nested data in its branches will trigger a re-render because the reference to root object has changed. And all state management libraries rely on reference checks to determine if something has changed.

In other words, any non pure-component or a component not wrapped inside React.memo() which uses Context API via useContext() etc., will re-render anytime there's a change in the global state. Redux and other state management libraries prevent this re-rendering from happening with nested states which can improve performance.

In a non-trivial app, using a state management library with memoized components can give you huge performance gains. Especially in a mobile app where you have a lot of data to show.

 
link2twenty profile image
Andrew Bone

Yeah that is heading the right way but when this changes it won't trigger a redraw though, which is the whole point of react. You can use local/session storage though.

 
link2twenty profile image
Andrew Bone
Collapse
 
zaimazhar97 profile image
zaimazhar97

Hi...
I am a beginner Vue guy, sorry I invaded to this post.

My question is kinda general tho...

For example, if one of our component holds the state of username and we accidentally forgot to include that component in certain pages that requires username state. Will the state of username actually gone when we visit the page with that missing component? I've never build a huge application with moving states from one component to others. I just store the state inside localStorage and access it whenever I want but sometimes it bothers me that user can manipulate the state by injecting their own JS script inside the console.

The question is, what is the best approach if I want to keep the state globally while still able to access/manipulate it easily?

Thanks.

Collapse
 
link2twenty profile image
Andrew Bone

Hi, no need to apologise the more the merrier 😅

If we're talking about Vue specifically I'm afraid I don't really know it well enough to answer. I can link you to their documentation on state management though.

State Management — Vue.js

Collapse
 
zaimazhar97 profile image
zaimazhar97

Thank you ☺️

Collapse
 
jamesthomson profile image
James Thomson

I just store the state inside localStorage and access it whenever I want but sometimes it bothers me that user can manipulate the state by injecting their own JS script inside the console

Just to be clear, this is the case regardless of if you're using localStorage or a state management lib. Anything on the client should be considered accessible to the user.

Collapse
 
zaimazhar97 profile image
zaimazhar97

I've been bugging myself for quite some time about this. Now I can stop concerning too much about keeping state in localStorage.

Thank you. 🙂

Thread Thread
 
jamesthomson profile image
James Thomson

Yes, don't worry about it unless it's sensitive information - that should never be stored on the client.

Collapse
 
molimat profile image
Molimat

I totally agree that context api should be enough, but it has a lot of boiler plate and some times it's difficult to make it organize. That's why I like the way recoil and mobx manages it.

Collapse
 
bolonhadev profile image
Bolonha Dev

Context + intelligence + reactive programing works for me.

Collapse
 
andykras profile image
Andrey Krasnov

I'd prefer to use composition and render-props in this example.

Also I'm wondering why did you name your components function App, is this a typo?

Anyway agree with you that sometimes context API is a fairly good replace of complex state management.

Collapse
 
link2twenty profile image
Andrew Bone

Yeah the example I made was very simplistic and not one you'd use out in the wild but the principle is the same.

The naming of the components was just me writing a quick demo, the code is not production ready, that being said I've updated the function names now.

Collapse
 
asologor profile image
Andrew Sologor

Firstly, you are not the first guy with such idea. Secondly, I agree with sgoulas. You NEED a state management library for the global state. Just because context wasn't created for global states. If you somehow avoid redundant re-renders of everything, it will eventually become unmanageable.

Collapse
 
link2twenty profile image
Andrew Bone

100% I am not the first person to think of this but I'm just sharing my take on it because a question was asked.

I'm yet to have a project where using context to handle global state has become overly complex, though you do have to think about the context and plan out the app first.

Thank you for your input

Collapse
 
rakeshsinghjamwal profile image
rakeshsinghjamwal • Edited

Honestly, I haven't still learned any state management library yet. I am still working with context api, useReducer and yet don't feel the need to use one. But may be in one of the upcoming projects I will be using one. More than a state management library I am more keen to learn data fetching library like react-query.

Collapse
 
evanburg profile image
Evan Burgess

I largely agree with this. Only on very large projects where complex state management is necessary do I ever reach to implement Redux or alternatives.
React Context provides a great interface that many will feel comfortable with out of the box and will be enough in about 80% of scenarios really.