Using Context to Handle Multi-Component State
React's context feature is one that allows you to create a value that can easily be shared across as many components as needed, without using props.
Using the context API is a multi-step process, the steps for which are described here:
- You must create a context value that should be shared.
- The context must be provided in a parent component of the components that need access to the context object.
- Components that need access (for reading or writing) must subscribe to the context.
React manages the context value (and its changes) internally and automatically distributes it to all components that have subscribed to the context.
Before any component may subscribe, however, the first step is to create a context object. This is done via React's createContext()
function:
import { createContext } from 'react'; createContext('Hello Context'); // a context with an initial string value...