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.
<Provider> and set prop
value to 0:
<Provider> as the top-level component in
Get the Provider
Create a reducer function:
Pass state and dispatch from
useReducer to Provider prop
<App> with the new context value:
An alternative to
useContext is Consumer.
Consumer from Context:
<Consumer> requires a callback function for prop
children. The 1st argument is the Provider
For class components, the Provider value can be accessed on
Ideas for improvements:
- Build a custom hook for
- Refactor action types to constants.
- Create action creators.
displayNameon Context to improve visibility in React DevTools.