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 to use for global data that you might need in multiple components through your component treeāfor example, a theme or authenticated user.
Context is created using the createContext
method and it 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 that 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, therefore...