×

How to use React Context

React Context

React Context is used to pass the data through the component tree without passing the props down manually at the every level.

In React Application, the data is passed in a top-down approach via props. Sometimes it is not convenient for some props that are required for the many components of the React application. Context gives you a way to pass the values between the components without passing the prop by every level of the component tree.

How to use Context

There are two steps by which you can use the Context in the React Application:

  1. Set a context provider and define the data which you want to store.
  2. Whenever you required the data from the store, then use the context consumer.

When to use Context

Generally, Context is used for sharing the data, which considered 'global' for the react component tree and uses that data wherever required. The data can include the authenticated user name, theme, etc.

In the following example, we manually thread by a theme prop for styling the Button component.

class App extends React.Component { 
render() { 
return ; 
} 
} 
function Toolbar(props) { 
return ( 
); } class ThemedButton extends React.Component { render() { return

In this code, the Toolbar function component takes the extra theme prop and passes it to ThemedButton. It will be inconvenient if each button in the application requires the theme because it would be required to pass by all components. But with the help of Context, you can avoid the passing of props for each component by intermediate elements.

You can understand it from the following example in which the Context passes the value in the component tree without threading it explicitly by every single component.

// Create a context for the current theme (with "light" as the default).
const ThemeContext = React.createContext('light');
class App extends React.Component {
render() {
// Use a Provider for passing the current theme to the below tree. Any component can read it.
// In this example, we're passing "dark" as the current value.
return (


 
);
}
}
// A component in the middle doesn't need to pass the theme explicitly. 
function Toolbar(props) {
return (
); } class ThemedButton extends React.Component { static contextType = ThemeContext; render() { return

React Context API

It is a component structure that allows you to share the data across all levels of the application. The Context API is mainly used to solve the prop drilling (also known as the 'Threading’) problem.

React.createContext

As its name implies, it is used for creating the context object. When React renders the component that subscribes to this context object, then it will read the value of current Context from the closest matching provider in the component tree.

Syntax:

const MyContext = React.createContext(defaultValue);  

The defaultValue argument is used only when the component has not a matching provider in the component tree. It is helpful to test the components in isolation without wrapping them.

Context.Provider

Every Context object includes a provider react component that allows consuming the components for subscribing to the context changes. It is like a delivery service. When the consumer component requires something, then it can be easily found that within the Context and give it to where it is required.

Syntax:

  

It accepts the prop value and passes to consume the components that are descendants of this provider. A single provider can be connected to many consumers. Context providers can be nested to override the values deeper in the tree.

All of the consumers that are descendants of the provider will re-render if the provider’s ‘value’ prop changes.

Class.contextType

The contextType property on a class is used for assigning the context object, which is created by the React.createContext(). It allows you to consume the nearest current value of that context type by using this.context. It can be referenced in any of the component lifecycle methods, including render function.

Context.Consumer

It is a react component that subscribes to context changes. It allows you to subscribe to a context in a function component. It requires the function of a child. The function receives the value of the current Context and returns a react node. A consumer is used for requesting the data by the provider and manipulates the central data store when the provider allows it.

Syntax:


{value => /* render something which is based on the context value */}
 

The ‘value’ argument in the above syntax passed to the function will be equivalent to the value prop of the nearest provider for this Context in the component tree. If there is no provider for this Context, then the value argument will be equivalent to the defaultValue that has passed to createContext().

Context.displayName

The Context object accepts the displayName string property. The React DevTools uses this string for determining what to display for the Context.

For example:

const MyContext = React.createContext(/* some value */);
MyContext.displayName = 'MyDisplayName';
 // It will display as a "MyDisplayName.Provider" in DevTools
 // It will display as a "MyDisplayName.Consumer" in DevTools 

React Context API Example

Let us try to understand the React Context by using the following example:

First, create a new react app by using the following command:

npx create-react-app mycontextapi

Now, install the bootstrap CSS framework by using the following command:

npm install react-bootstrap bootstrap --save
React Context API Example

Add the following code in App.js file:

import React, { Component } from 'react';  
import 'bootstrap/dist/css/bootstrap.min.css'; 
const ButtonContext = React.createContext('btn btn-darkyellow'); 
class App extends Component { 
render() { 
return ( 
 
; 
} 
} 
export default App;  

In the above code, we have created the Context by using the React.createContext(), which returns the Context object. Then, we have created the wrapper component, which gives the provider component and further adds all the elements as the children from which we require to access the Context.

Output:

On executing the above code, the output will be:

On executing the above code

Related Topics

Difference Between React Flux and MVC

React Flux vs MVC MVC MVC is an acronym of 'Model View Controller.' It is the architectural pattern that is used to develop the user interface. It has three different logical components: The...

2 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

React Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

React CSS

What is React CSS React CSS is used to provide the style to the React applications. The style attribute adds dynamically-computed styles at render time, and it is one of the most used...

5 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

2 minutes read.

Difference Between State and Props in React

Comparison between State and Props State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over...

2 minutes read.

React State

React State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change...

3 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

ReactJS Tutorial

ReactJS Introduction React Tutorial helps you to understand the basic and some advanced concepts of ReactJS. As of now, it is the essential front-end library that is developed by a...

3 minutes read.

React Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 minutes read.

React Props

React Props A prop is an abbreviation of ‘properties.' State and props are mainly different from each other because props are immutable. Props are the read-only components. It is the object that stores the attribute...

3 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

React Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 minutes read.

Features of ReactJS

ReactJS Features As of now, within the developers, ReactJS is gaining much popularity as the best JavaScript framework. It is crucial for the front-end ecosystem. There are some of the crucial features of ReactJS that are...

2 minutes read.