For a long time, I used to think of React Context as a state management tool. But much later, I learned why it was NOT...
From the very moment the Context API was released, we've been seeing claims like:
But that's mostly incorrect. Here is why:
For something to be considered a "state management tool", it needs to be able to:
But does the Context do any of that itself??
Nope. It doesn't.
The thing that usually do that is a bunch useState/useReducer(s), & the Context only passes down their values & the update functions without props drilling, and that's it!
Becaues in reality, you can do whatever you are doing using your (useState/Reducer + passing props) without touching the Context at all, and you would almost get the same results. So the context isn't doing anything state related, thereby it's not a state management tool!
"But when you use Context, you get fewer re-renders!" True. But not very much. When the state that you are passing down isn't simple, any change to any part of it will cause the entier consumer's trees to re-render, even if they don't care about the updated value.
"But you can throw a bunch of memo(s) around to reduce the number of unnecessary rerenders to the consumers children!!" True. But not very much. If your components are passing callback functions or objects as props to their children, then memo() wont do anything. Unless you want to also throw a bunch of useCallback & useMemo around too. 😒
"You can also split your Context into multiple smaller Contexts to reduce rerenders!" True. This can to some extent save some re-renders, but to which extent?? Because honestly, at this point, you are almost re-inventing a state management solution from scratch, but only not as good...
"But Redux also uses Context under the hood!!" True. But not in the same way. When you use Context + useState/Reducer, you are using the Context to pass down the current state value.
Redux however, uses the Context to pass down its store instance, not the store state. The consumers will later access this store and subscribe to whatever piece of state they need. But the store object itself almost never changes.
"So when should I use Context??" Context is Best when you are passing:
Fortunately, most common apps won't usually need more. But in the other cases, then you should consider using a state management tool.
And that's everything folks.
Leave a like if you found this helpful 👍, And have a nice day 👋.
About Me
I'm a freelance web developer who specializes in frontend.
I have a special love for React. And my personal goal is: Building things that are Awesome! ✨
If you are someone who is building a project where high quality is a MUST, then Let's Chat! I'll be glad to help you with it.