Who said that the Context API can only handle simple state??

"The Context API is NOT good for handling complex state needs"

If you tried the Context API in a real-world project with a somewhat complex state, you might have thought that.

And for a long time, I've thought that too!!

However, I learned later that this might not be entirely true...

Whenever we start building a new context provider, we start creating some state vars with useState(s), then add some events handlers functions, and finally we pass them to the provider's value prop. And this works well enough for when we only have a few state variables & handlers.

But as more requirements are introduced, more useState(s) are added, more event handlers created, and things gets very messy very quickly... It becomes hard to debug and figure out who is changing what, & some weird bugs will start appearing in certain cases without really knowing why & or what caused them.

So because of that, a lot of developers just avoid the Context API altogether, & instead go to an external state management library like Redux.

But please wait!!!

Before you do that, let me tell you about a way that will still keep your state manageable even when it starts getting bigger, and who knows, you might not need a new state library!!

The way I'm talking about is basically: To replace your useState(s) & callback functions with a useReducer hook.

With this, you will only have one way to change your state (using dispatch), the actions are clearly defined, and it's a lot more debuggable.

In fact, the React team also recommends this approach in their new docs for handling complex state here

So try it out, and maybe you will realize that you most likely don't need a state management library anymore!!!

Okay, that's it for today folks.

Until next time, and have a nice day 👋

My Photo

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.

© 2023-present Mohammed Taher Ghazal. All Rights Reserved.