Managing React state with Context

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:

Provider

Create <Provider> and set prop value to 0:

useReducer

Create a reducer function:

Consumer

An alternative to useContext is Consumer.

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

--

--

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