The other day I was browsing LinkedIn when a poll caught my eye
What's your favourite React State Management Library and why?
Naturally, I fe...
For further actions, you may consider blocking this person and/or reporting abuse
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.
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.
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/...
Yes, I know context isn't a state management solution hence saying
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 π
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.
hello buddy I have a question
Hello, I am not sure I understand the question.
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 requiresusername
state. Will the state ofusername
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.
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.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. π
Yes, don't worry about it unless it's sensitive information - that should never be stored on the client.
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
Thank you βΊοΈ
I use Redux in my React apps for one and only one purpose: to store in app memory the JWT when handling authentication (because saving it in local storage would be madness). And I chose Redux because it was very popular a few years ago.
I also use React Context to store app wide config info like theming, language. However I do not use any other "global" state,
react-query
is more than enough for displaying API results in the frontend.Cheers!
It sounds like you don't need redux π€
That may be true, but what else? I need something non persistent to store some app state and I believe Redux is just that: a state container
You can put it with the rest of your app state, or send it through another context provider.
Of course. But I wanted decoupled from my app state because I can reuse this principle for other apps that do not use React. It never actually happened until now but that's what I thought when I decided to use Redux: to keep things completely separated.
Use what makes you happy,
after all, you'll be the one debugging when anything goes wrong in your app
Hey Victor, great post !
If you're using
react-query
/react-swr
for data fetching/caching then Context API will be enough for managing the simple UI statesI 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?
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.
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
I use
zustand
in this case. It's the most efficient in this caseHard 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.
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
It was a tweet.
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?
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.
Zustand is simple to learn and powerful. Easy manipulation inside and out of components. Very little boilerplate. Many performance optimizations baked in.
I've never heard of Zustand, what would you say its main benefits are?
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.
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?
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?
In my humble opinion I use state management only if a way back of the data is needed, e.g. the user is filling in the data and the next step modify the provided data however the user could go back to review the previous data again, cart applications and similar or microfrontend (well here you will find a lot of discussions for and against using data sharing via microservices).
Summing up every application where the user could close the browser and log in again and we want to have ready all the data that was provided.
If we don't have these situations, we are adding extra effort for nothing when the browser and JS tools would be enough (LocalStorage, SessionStorage, Cookies, Cache, etc)
There is a tendency to add state management in every application because it is cool and the applications are overkill.
I hope it helps.
Thanks.
My favorite is
overmindjs
which I would describe as if somebody who codes regularly rewroteredux
to be actually "ergonomic" without the false functional programming paradigm and with an actual smart TypeScript implementation that works. It still has issues with handling deep nested values, but it is many steps to the right direction.So to answer your question: in very simple cases you don't need a library. If your state grows, you have separate menus with their separate stuff, you will need namespacing, grouping. If you have complex set of state transformations (like having editing mode and then go back to preview mode) you will need a state machine as well (
overmindjs
also has it).I think why people want to get rid of state management libs are coming from design mistakes that made them not ergonomic.
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.
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.
O use a mix of local state, hooks/context and redux at work. We apply them where it makes sense to get the most of them. A complex hook may be better implement as a redux slice, in the same way a slice that doesn't implement async logic and has a fairly simple state is better off as a hook. The key is find the balance where a global state is needed and where you should keep the state local to the component. All depending on the size of tge application. π
Yes, when working for a Medium to big project redux makes life easier. And then redux-saga makes Api calls so much organised. And the biggest difference is Context API is expensive.Context API prompts a re-render on each update of the state and re-renders all components regardless. Redux however, only re-renders the updated components
Slight caveat Context API updates all components that use the specific context updated. Provided you split the data across several contexts and only import the context in components that need access the redraws become a non-issue.
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.
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
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, ..
I see some comment against Context API. It's definitely a feasible state management solution. Most of the current state management libraries already use Context API internally. In the end it's all about your use case, no one state management methodology is perfect or fits all purpose. It's all contextual based on factors like.
This article might help you choose the right solution based on your use case. dev.to/swyx/why-do-webdevs-keep-tr...
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.
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
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
This has the exact same outcome but will only need process time when the button is pressed rather than on every key stroke.
hello buddy I have a question
Zustand?
I've been using Recoil for a fairly large project, overall it's been really good. One issue is with tests it becomes a little bit of a struggle working with it because you can't read Recoil values in tests. Otherwise, it's been nice to have and a lot easier than other options we looked at.
I think we dont need State Management Libraries. React itself has everything necessary.
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.
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.
useContext and probably UseQuery from react-query are what I need.
What is it you like about useQuery? I tend to write my own fetch requests, even though that can lead to code repetition.
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.
Context + intelligence + reactive programing works for me.
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.
Here's an example I wrote using local storage
React: Custom hook for accessing storage
Andrew Bone γ» Apr 21 γ» 8 min read
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.