×

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 Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 minutes read.

React Components

React Components Former, the developers used to write more than thousands of lines of code to develop a single-page application. These applications follow the structure of traditional DOM, and it was very challenging to make...

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

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

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

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

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

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 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 Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 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 Redux

How to Use Redux with React Hooks It is an open-source library of JavaScript which is used for managing the application state. React uses the Redux to build the user interface....

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

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