DEV Community

Discussion on: Sharing state using React's Context API

Collapse
 
leob profile image
leob • Edited

I agree with you to keep state locally within the component, if that piece of state is only needed within that component. So don't make state "global" or centralized if it's needed only in 1 place. No disagreement there.

However ... I didn't know how the Context API works, but now that I know, it I wonder in what way it's really simpler than Redux. If I I understand it correctly, it's just an alternative way to have "global" or centralized state which you can access wherever you want, do I see that correctly?

In that case I would argue that conceptually it isn't really that different from Redux, only "syntactically" and in its mechanics, the way you program it - what it achieves it isn't that different. In the end both sort of look like a glorified way to inject a singleton object with some variables and getters/setters.

In other words, I don't really see the point, unless it cuts down a lot on "boilerplate". Redux also isn't that hard to understand or use, and it's a well known pattern. I'm never really a big fan of "10 different ways to do the same thing", it makes it a lot harder for (new) developers to understand an unfamiliar codebase.

(this is also why I'm generally a fan of the Vue framework - Vue is more opinionated and "batteries included" and mostly advises one recommended way of doing something)

Actually I could make the opposite argument: if you start out with "Context" because your app is 'simple', and later on you realize (as you said) that you'd better use Redux because your app has become more complicated, then you'll have to rewrite all of your context-based code to Redux. Then why not start with Redux right away? Especially because it isn't that hard, at least in my opinion.

So yes, I agree with you when you say "don't reach for Redux too early", but the same applies to Context - don't reach for Context too early. As long as you can manage state locally within components, or you just need to pass it down 1 or 2 levels (via props) then use neither Redux nor Context.

Once you realize that you do need centralized state, then use Redux or use Context, whatever floats your boat (but as I said I don't really see how Context is that much simpler than Redux).

Thread Thread
 
sunnysingh profile image
Sunny Singh

Ah I see what you mean.

Yes you're correct, there is no difference in what Redux and Context API are made to do.

I also definitely agree with local state. Don't reach for Context or anything global if your components don't need that yet.

The topic of whether Context is actually simpler or if it's better to use a well-known library like Redux is for another discussion I believe. There's also different ways of implementing Redux so I think even if I make some points against Redux, it may not actually apply to every project that uses Redux.