Managing React state with Context

remarkablemark
1 min readMar 21, 2021

YouTube:

CodeSandbox:

Motivation

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.

Prerequisites

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.

Provider

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>:

useReducer

Create a reducer function:

Pass state and dispatch from useReducer to Provider prop value:

Update <App> with the new context value:

Consumer

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.

Class

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

Todo

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.

Resources

--

--