AppDividend
Latest Code Tutorials

React Context API Tutorial: Everything You Need to Know

Context provides the way to pass data through the component tree without passing 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 a cumbersome and not good idea for certain types of props (e.g., locale preference, theme) 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.

Create a new React app using the following command.

npx create-react-app contextapi
cd contextapi
npm start

React Context API Tutorial With Example

When you start the react development server and find any error regarding webpack-dev-server, 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 the 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 button’s color is changed according to btn btn-info.

React Context API

Context is designed to share the data that can be considered 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, inside the App component, the nested component is Button. It is a stateless component, 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 the 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 the 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. Thus, it is beneficial to test components in 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 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 equal the defaultValue that was passed to createContext().

That’s it for this tutorial.

1 Comment
  1. benam says

    good job

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.