React Context API Tutorial With Example is today’s leading topic. Context provides the way to pass data through the component tree without having to pass the props down manually at every level. In the typical React application, data is passed top-down (parent to child) via props, but this can be the cumbersome and not good idea for certain types of props (e.g., locale preference, theme) that are required by many components within the application. The React team suggests sticking to props if you have just a few levels of children to pass because it’s still a much less complicated API than the Context API.

React Context API Tutorial With Example

Create a new React app using the following command.

npx create-react-app contextapi cd contextapi npm start

When you start the react development server and find any error regarding webpack-dev-server then you will find a solution in the terminal, if it works for you then best otherwise you can go for the below solution.

Create one .env file in root and add the following code inside it.

SKIP_PREFLIGHT_CHECK=true

Install the bootstrap 4 css framework also by the following command.

yarn add bootstrap # or npm install bootstrap

You create the context using React.createContext() , which returns the Context object.

const {Provider, Consumer} = React.createContext()

Then you create the wrapper component that returns the Provider component, and you add as children all the elements from which you want to access the context. Let us take an example.

Write the following code inside src >> App.js file.

// App.js import React, { Component } from 'react'; import 'bootstrap/dist/css/bootstrap.min.css'; const BtnColorContext = React.createContext('btn btn-dark'); class App extends Component { render() { return ( <BtnColorContext.Provider value="btn btn-info"> <Button /> </BtnColorContext.Provider> ); } } function Button(props) { return ( <div className="container"> <ThemedButton /> </div> ); } class ThemedButton extends Component { static contextType = BtnColorContext; render() { return <button className={this.context} > hello </button>; } } export default App;

You can see in the webpage output that the color of the button is changed according to btn btn-info.

Explanation of React Context API

Context is designed to share the data that can be considered as a “global” for the tree of React components, such as a current authenticated user, theme, or preferred language settings. We have done the following things in the above example. Let us see one by one.

First, we create a button class context and assign the btn btn-dark.

Then inside the App class, we have changed the value of the context to the btn btn-info.

Now, the inside the App component, the nested component is Button. It is a stateless component, means just a functional component, which receives the props as an argument.

Now, inside that component, we have one more nested component called ThemedButton. But we have not passed any property from Button component to ThemedButton.

So, now if we want to access the value of the button class, which we have defined in the React context, then we need to write the following code inside ThemedButton class.

class ThemedButton extends Component { static contextType = BtnColorContext; render() { return <button className={this.context} > hello </button>; } }

So, we have defined the static contextType and use the current context value by this.context, and now we can see the latest context value, which is described in this code.

<BtnColorContext.Provider value="btn btn-info"> <Button /> </BtnColorContext.Provider>

Now, if we write the above code like this then see the output on the result.

<div> <Button /> </div>

Save the file and see the button color. It will change to dark according to defined the react context. That means, if we modify the context in between parent to children flow then it will take the latest value otherwise it will take the first defined value.

React Context API

1. React.createContext

You can create the context using the following syntax.

const MyContext = React.createContext(defaultValue);

Creates a Context object. When React renders the component that subscribes to this Context object, it will read the current context value from a closest matching Provider above it in the tree. We have used this in our example to change the button class from dark to info.

The defaultValue argument is only used when the component does not have the matching Provider above it in the tree. It is very helpful for testing components in the isolation without wrapping them. Please Note here that passing undefined as a Provider value does not cause consuming components to use defaultValue.

2. Context.Provider

The syntax is following.

<MyContext.Provider value={/* some value */}>

Every Context object comes with the Provider React component that allows consuming components to subscribe to the context changes. Accepts the value prop to be passed to the consuming components that are the descendants of this Provider. One Provider can be connected to the many consumers. Providers can be nested to override the values deeper within a tree. As we have overridden the default value of the className and we get the latest value of the className in the component tree.

3. Context.Consumer

The syntax is following.

<MyContext.Consumer> {value => /* render something based on the context value */} </MyContext.Consumer>

It is the React component that subscribes to the context changes. It lets us subscribe to the context within the function component. Requires the function as a child.

The function receives a current context value and returns the React node. The value argument passed to a function will be equal to a value prop of the closest Provider for this context above in the tree. If there are no Providers for the context above, the value argument will be equal to the defaultValue that was passed to createContext().

Finally, React Context API Tutorial With Example is over.