React Context API: Everything You Need to Know

1
33
React Context API Example Tutorial

In the typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome and not good for specific 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.

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;

In the web page output, you can see that the button’s color is changed according to btn btn-info.

React Context API

React 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. Context allows passing data through the component tree without giving the props down manually at every level.

Let’s understand the React context using an example. First, we create a button class context and assign the btn btn-dark. 

Then inside the App class, we changed the context’s value to the btn btn-info.

Now, inside the App component, the nested component is Button. It is a stateless component, just a functional component, receiving 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 used the current context value. We can now see the latest context value described in this code.

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

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. For example, if we modify the context between parent to children flow, then it will take the latest value. Otherwise, it will take the first defined value.

How to create Context in React

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. In our example, we have used this 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 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. We have overridden the default value of the className and 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 passed to createContext().

That’s it for this tutorial.

1 Comment

Leave A Reply

Please enter your comment!
Please enter your name here

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