YogeshChauhan . com

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to hide and show menu on scroll using JavaScript and CSS?CSSHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPKilling A Project Part 4: What Would Be Your Top 3 Priorities For Planning The Cancellation?MiscIf statement shorthand examples in JavaScriptJavaScriptSelect statement in Postgres with examplesPostgresfirst-of-type and last-of-type selectors in CSSCSS