React context: The definition and how to use it effectively for your business

If you’re having a problem with passing property to a component just to pass it further down to the child, React Context is exactly what you need. This API has become the state management tool of choice for many, oftentimes replacing Redux altogether. Also, by having this on your eCommerce website, this component will help you manage global application states in your React apps without resorting to props drilling.

React Context introduction and usage
React Context introduction and usage

To clarify, React Context provides us a possibility to pass data through the component tree. So, you don’t need to pass props down manually at every level. In other words, we can compare context to a global object of our React App. So now, we – ArrowHiTech would like to introduce to you guys a little bit about the definitions, as well as the steps on how to use this module effectively for your business.

Let’s get into it!

What is the definition for React Context?

Context certainly provides a way to pass data through the component tree without having to pass props down manually at every level. In other words, it provides a way for you to make particular data available to all components throughout the component tree no matter how deeply nested that component may be.

The context is certainly based on the hooks, which, according to the React Docs, are a new addition in React 16.8. They let you use state and other React features without writing a class instead.

>>> Read more

React router vs reach router: Which should you use for your business?

OpenCV: Features and how to use it in React native for image processing

Some benefits of React Context API

When we need to make some of the data global in our app, or we would like to use them in a few components on a different deeply nested levels in the app structure, we definitely should use React Context. Also, When we need to pass prop through a lot of components and it becomes a little bit annoying, React Context will come to the rescue. It certainly gives us access to the data on each level of our React App tree structure.

Also, we want to build a “theme toggler” component which toggles between modes for our React app. Every component has to have access to the current theme mode so they can be styled accordingly. As a result, Context could help you with that.

How to use React Context effectively?

In order to demonstrate this, we will create this funky (and super useful) day-to-night switching image:

#1. Creating React context

Firstly, we create a new Context. Because we want the entire app to have access to this, we go to index.js and wrap the app in ThemeContext.Provider. We also pass the value prop to our Provider. This certainly holds the data we want to save. But for now, we just hardcode in ‘Day’.

 import React from "react";
import ReactDOM from "react-dom";
import ThemeContext from "./themeContext";

import App from "./App";

ReactDOM.render(
  <ThemeContext.Provider value={"Day"}>
    <App />
  </ThemeContext.Provider>,
  document.getElementById("root")
);

#2. Consuming React Context with contextType

Currently, in App.js, we are certainly just returning the image component.

 import React from "react";
import Image from "./Image";

class App extends React.Component {
  render() {
    return (
      <div className="app">
        <Image />
      </div>
    );
  }
}

export default App;

The goal is obviously to use React context to switch the classNames in Image.js from Day to Night, depending on which image we want to render. To do this, we add a static property to our component called ContextType instead. After that, we want to string interpolation to add it to the classNames in the image component. So now, the classNames contain the string from the value prop. 

 import React from "react";
import Button from "./Button";
import ThemeContext from "./themeContext";

class Image extends React.Component {
  render() {
    const theme = this.context;
    return (
      <div className={`${theme}-image image`}>
        <div className={`${theme}-ball ball`} />
        <Button />
      </div>
    );
  }
}

Image.contextType = ThemeContext;

export default Image;

#3. Extract Context provider

We are certainly passing a hard-coded value down through the Provider. However, our goal is to switch between night and day with our button. This likewise requires moving our Provider to React Context to a separate file and putting it in its own component. In this case, called ThemeContextProvider. One thing to remember: the value property is now being handled in the new file ThemeContext.js, and should, therefore, be removed from index.js.

 import React, { Component } from "react";
const { Provider, Consumer } = React.createContext();

class ThemeContextProvider extends Component {
  render() {
    return <Provider value={"Day"}>{this.props.children}</Provider>;
  }
}

export { ThemeContextProvider, Consumer as ThemeContextConsumer };

#4. Changing the Contextv

To wire up the button, firstly, we add state to ThemeContextProvider. Then, add a method for switching between day and night:

 toggleTheme = () => {
  this.setState(prevState => {
    return {
      theme: prevState.theme === "Day" ? "Night" : "Day"
    };
  });
};

Now we change our value property to this.state.theme so that it returns the info from the state. Then, we change the value to an object containing {theme: this.state.theme, toggleTheme: this.toggleTheme}. Also, we update all the places where we use a single value to look fora theme in an object. This means that by using React Context, every theme becomes context as a result. Also, every reference to the theme as value becomes context.theme.

Finally, we tell the button to listen for the onClick event and then fire context.toggleTheme. This, to clarify, updates the Consumers who are using the state from the Provider. So, the code for the button looks like this:

 import React from "react";
import { ThemeContextConsumer } from "./themeContext";

function Button(props) {
  return (
    <ThemeContextConsumer>
      {context => (
        <button onClick={context.toggleTheme} className="button">
          Switch
          <span role="img" aria-label="sun">
            ?
          </span>
          <span role="img" aria-label="moon">
            ?
          </span>
        </button>
      )}
    </ThemeContextConsumer>
  );
}

export default Button;

That should do the trick, all in all.

Final words

That should be it! To conclude, here is everything about the React Context, and how to use it effectively. By providing an intuitive example, it would obviously be easier to put the state in the app and pass it down via props. Also, this module can show the power of having consumers who can access data independently of the components above them in the tree. As a result, that will help you a lot in your business.

Tags

Share