-
Book Overview & Buying
-
Table Of Contents
React and React Native - Sixth Edition
By :
React applications often have a few pieces of data that are global in nature. This means that several components, possibly every component in an app, share this data: for example, information about the currently logged-in user might be used in several places. This is where the Context API comes in handy. The Context API provides a way to create a shared data store that can be accessed by any component in the tree, regardless of its depth.
To utilize the Context API, we need to create a context using the createContext function from the React library:
import { createContext } from ‘react’;
const MyContext = createContext();
In the preceding example, we create a context called MyContext using createContext. This creates a context object that contains a Provider and a Consumer.
The Provider component is responsible for providing the shared data to its child components. We wrap the relevant portion of the component tree with the Provider and...