Yogesh Chauhan's Blog

How to use Context in React?

in React on May 28, 2021

With context you can pass data through the components without passing props manually at the entry level.

React has a data flow and it’s a top-down or parent-child approach but you might not want to follow it every single time especially while developing UI themes or similar apps. Because those kind of apps have many components and it becomes hard to follow that top-down data flow.

That’s when context comes into rescue. You can use context to share data between components bypassing that top-down data flow explicitly.

Example Without Context

This is how we do it without using context:

In the example below, the toolbar component takes a theme prop and pass it to the ThemeButton.


class App extends React.Component {
  render() {
    return <Toolbar theme="dark" />;
  }
}

function Toolbar(props) {
  return (
    <div>
      <ThemedButton theme={props.theme} />
    </div>
  );
}

class ThemedButton extends React.Component {
  render() {
    return <Button theme={this.props.theme} />;
  }
}



Imagine how much complicated task it will become to pass theme to every single button we add.

Contexts are like global variables defined by the user and can be used anywhere in the app.

Example With Context

Let’s use content now so that we can finally avoid passing the props in those intermediate elements.

Step 1: Create Context

Let’s create a context for the current theme and “light” as the default value.


const ThemeContext = React.createContext('light');

Give the gift of Audible

Step 2: Use a Provider

Now, we need to use a Provider to pass the current theme. Any component can read the theme and modify the default value. Let’s add a “dark” value to it.


class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}



Step 3: Assign a contextType

Now, we need to read the current theme context and to do so we need to assign a contextType. Once we do that, React will find a closest Provider above and then grab it’s value to use it.


class ThemedButton extends React.Component {
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}


Bringing all together


const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}


Credit: React Docs


Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
A quick introduction to API, REST API and PostmanMiscellaneousThe Difference Between the echo and print Commands in PHPPHPVariables and Distance Functions in SCSS (Sass)SCSSSolution for “Yarn build: Failed because of a stylelint error”WordPressPHP __construct() functionPHPHow to merge arrays in JavaScript?JavaScript