DEV Community

Cover image for React useContext and useReducer Hooks.

React useContext and useReducer Hooks.

EswaraPrakash Vaithiyanathan on July 24, 2021

A simple example of React useContext and useReducer Hooks available in React that can be used as a replacement for Redux. Instead of usi...
Collapse
 
boywithsilverwings profile image
Agney Menon

While this is a bare state management mechanism, it is not a replacement for redux. Here all components subscribed to the context will rerender when any value in the context changes.

When you use redux, only the components subscribed to that particular state rerenders on state change - even though there is a single global store.

Collapse
 
korneldoe profile image
Kornel

Good point. Is there a way to use something to prevent the subscribed components to rerender if not needed? Thinking about something like memo where it does shallow comparison on props object?

Collapse
 
ritikbanger profile image
Ritik Banger

What if the context api is used with reducer? more complex but interesting thing to do.

Collapse
 
sjiamnocna profile image
Šimon Janča

Well, nice article.
Now, I'm missing the part with async actions...

Some other article I read suggested for better performance to divide the Store context and the Dispatch event context as whenever the context changes all components rerenders. But these dispatch methods shouldn't change over runtime...

Collapse
 
lalami profile image
Salah Eddine Lalami

@ IDURAR , we use react context api for all UI parts , and we keep our data layer inside redux .

Here Article about : 🚀 Mastering Advanced Complex React useContext with useReducer ⭐ (Redux like Style) ⭐ : dev.to/idurar/mastering-advanced-c...

Mastering Advanced Complex React useContext with useReducer (Redux like Style)

Collapse
 
itays123 profile image
Itay Schechner

That's awesome. I myself don't really like Redux and I recently used a similar solution in one of my applications. When using Websocket, this is a game changer.

Collapse
 
eswaraprakash profile image
EswaraPrakash Vaithiyanathan

Thanks. Yes, React is evolving pretty good by reducing the dependencies on other libraries. Will post a new featured article about the latest changes very soon.

Collapse
 
nj23 profile image
NJ Nath

Really helpful

Collapse
 
imamdev_ profile image
Imamuzzaki Abu Salam

Thanks a lot for sharing 💖

Collapse
 
korneldoe profile image
Kornel

Good read.

Question: what is the cons and pros between using useReducer with Context API vs using simple useState hook?

Collapse
 
ebitzu profile image
eBitzu

useState is not recommended for storing object state