Managing React state with Context

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 —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 and set prop to 0:

Render as the top-level component in :

Get the Provider with in :

useReducer

Create a reducer function:

Pass state and dispatch from to Provider prop :

Update with the new context value:

Consumer

An alternative to is Consumer.

First, export from Context:

Then replace with :

requires a callback function for prop . The 1st argument is the Provider .

Class

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

Todo

Ideas for improvements:

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

Resources

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