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:


Create <Provider> and set prop value to 0:


Create a reducer function:


An alternative to useContext is Consumer.


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