The context API allows us to share the data between components without passing data using the state management like Redux or MobX.
In practical examples, we can use it share data like device settings, language preference (most famous example), authentication or user necessary information.
In our case, we’re going to use user and language info.
Steps:
- Use create-react-app
- Create a context folder
- Create language context and Auth context
- Expose consumer and provider (AuthConsumer, AuthProvider, LanguageConsumer, LanguageProvider)
- Add User info (sign in, signup)
- Change language preference
Context API Legacy to 16.3 :
Context API was available in the older version of REACT but it’s was not recommended. Since mars 2018, the React team publish a new version 16.3 using RenderProp
pattern to pass data to the children.
How it works:
- Language Context (Exposing Provider & Consumer)
- Auth Context (Exposing Provider & Consumer)
We expose both of them in the index.js
in the context folder
import * as Auth from “./auth”;import * as Language from “./language”;export { Auth, Language };
That helps to access from every Provider and Consumer by only importing the context like this import * as Context from '../context';
and use like in this example below.
As we can see it’s not really practical to have to handle multiple render prop, nested render prop. And if can be really messy if you use in a class component. So the team decide to add a new way to consume de context value with static contextType
static contextType —React v16.6
This API allows us to subscribe to a context and have access to the value using this.context
but we can only subscribe to one and one Context. To use multiple context, we have to use the example above using render prop pattern :-).
First of all we’re going to expose our LanguageContext
created with React.createContext()
.export const LanguageContext = React.createContext();
Our component class should look like
What’s Next:
- Test the React Hooks (useContext, useState, useReducer, useEffect)
- Test React.memo React.lazy
Thanks for your time, CLAP and SHARE if you enjoy this article and HIT ME UP FOR FEEDBACKS ❤