Managing React state with Context




Why use Context to handle React state? The same reason you use Redux to manage your application store. If your components talk to one another and lifting state becomes cumbersome, then Context is a native way to deal with your application state.


We will be refactoring <App>—which uses local state—to use Context:

As you can see, there’s a counter with 2 buttons that increments or decrements the count.


Create <Provider> and set prop value to 0:

Render <Provider> as the top-level component in index.js:

Get the Provider value with useContext in <App>:


Create a reducer function:

Pass state and dispatch from useReducer to Provider prop value:

Update <App> with the new context value:


An alternative to useContext is Consumer.

First, export Consumer from Context:

Then replace useContext with <Consumer>:

<Consumer> requires a callback function for prop children. The 1st argument is the Provider value.


For class components, the Provider value can be accessed on this.context:


Ideas for improvements:

  • Build a custom hook for useContext(Context).
  • Refactor action types to constants.
  • Create action creators.
  • Set displayName on Context to improve visibility in React DevTools.


Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store