×

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

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.

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.

Difference between Controlled and Uncontrolled component in ReactJs

Controlled Component In the controlled component, the input of the form element is handled by the component rather than the DOM. Controlled components have the functions that govern the data, which...

2 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 Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

3 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 minutes read.

React Higher-Order Components

React Higher-Order Components In short form, Higher-Order Components are represented as HOC. The Higher-order component is an advanced technique to use component logic. HOC is a function that takes the component and returns the new...

2 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.

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

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.

React Fragments

React Fragments The fragments in React are introduced from the 16.2 and above versions. Fragments allow you to group a list of child elements without adding any extra node in the DOM. In React,...

2 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 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 Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.

React Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 minutes read.

React Keys

React Keys A key can be defined as a unique identifier. In React, it is used for identifying the items that have changed, deleted, and updated from the lists. React Keys are helpful...

3 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.

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.

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...

4 minutes read.