Using Context to Share State
For our app, weâre going to use two React hooks to help us share state. The first hook weâre going to use is useContext, which lets us use a feature of React called a context. In React, contexts allow us to share global data among components without passing that data via props.
To use a context, we surround our code with a special JSX component called a context provider. The context provider is initialized with a value, and then any component inside that provider, no matter how many levels down, can use the useContext hook to give that component access to the data in the context.
The specific data we want to share in our context is a reducer function that will provide our common state and a dispatch function ...
Get Modern Front-End Development for Rails, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.