As you probably know, version 16.3 of React was released around March. In this article, we are going to talk to you about a new feature that is generating a lot of discussion within the React community: the Context API.
What is it and how does it work?
This API has one specific purpose: to send properties down to your child components from any parent component, without necessarily going through an intermediary.
The API is initialised with the React.createContext function, which returns a Provider corresponding to the parent component, as well as a Consumer, corresponding to the child component. Whereas previously it was necessary to go through several providers in order to connect the consumer to the desired provider, this API makes it possible to link the child directly to the parent without getting into overly complex connections.const {Provider, Consumer} = React.createContext(defaultValue);
Now that we have explained how the Context API is initialised, we are going to look at initialising the Provider and the Consumer.
The Provider
This component is the one located highest up in the context, or even in the application. Its particular feature is that it subscribes the Consumers to context changes. It can also be connected to several consumers (child components). Its value corresponds to the properties that will be broadcast to the Consumers.
You can declare a provider as follows:
The Consumer
The Consumer is the element that will receive the property from the Provider. It subscribes to context changes. In order to retrieve the properties broadcast by the Provider, the Consumer must use a function as a child in order to use the shared properties. Here is an example below.{value => /* render something based on the context value */}
Application examples
You will find here an example of the API in use. You will find the creation of a context, as well as the initialisation of a provider and a consumer (source: reactjs.org).
theme-context.js
See the Pen bKPzXq by Aaron (@leox47) on CodePen.
themed-button.js
See the Pen GGbeKo by Aaron (@leox47) on CodePen.
app.js
See the Pen MXMxgG by Aaron (@leox47) on CodePen.
We publish other technical articles dedicated to React on our blog; do not hesitate to follow us and subscribe to our LinkedIn page.