The Context API
Passing data using props can be cumbersome if your component tree is deep and complex. You have to pass data through all components down the component tree. The Context API solves this problem, and it is recommended for use with global data that you might need in multiple components throughout your component tree – for example, a theme or authenticated user.
Context is created using the createContext
method, which takes an argument that defines the default value. You can create your own file for the context, and the code looks like this:
import React from 'react';
const AuthContext = React.createContext('');
export default AuthContext;
Next, we will use a context provider component, which makes our context available for other components. The context provider component has a value
prop that will be passed to consuming components. In the following example, we have wrapped <MyComponent />
using the context provider component...