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');

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 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
File System Integrity: How to Keep an Eye on Your Files and Folder Change?MiscellaneousSome interesting HTML Input Attributes to rememberHTMLWhat is ECMAScript?JavaScriptWhat are “holes” in a React component?ReactHow does AdSense calculate page loading time?JavaScriptHow to Pop an Alert Box in PHP?JavaScript