Posted on October 3rd 2020 in React by Pim Debaere.
Passing Props with Context
In most applications properties are passed, from parent to child, so they can be used some levels deeper. This can sometimes seem inconvenient, especially when you have to pass properties to a lot of components. Thanks to React's Context API, this is easy to avoid.
Context API
An example: your application has two possible themes, namely a "light" and a "dark" theme. It is therefore logical that all components use the same theme, so we give pass this property from our main component (App).
Note in particular that we have to provide the same property for each ThemedButton. So let's take a look at the Context API to do this more elegantly. There are four things we should use.
React.createContext: components subscribing to a particular context object will read the values as they are currently in the closest Provider object in the parent tree.
Context.Provider: each Context has a provider that components can subscribe to if they want to use it. All components that use this Provider will be rendered again if they change.
Class.contextType: this property allows the component to consume the nearest value.
Context.Consumer: a component that subscribes to a context is seen as a consumer.
Knowing this, we can rework the example above and get the following: