Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

react
context

What is React context?

Martin Tiangco

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

React context allows sharing data between React components without passing down props.

The regular method of sharing data in React applications is passing data as props from a parent to their children. However, there are some data types used in multiple (and maybe unrelated) components, and passing that data to those components can make the code hard to read and maintain. Examples of these data include locales, user authentication, and UI themes.

It was introduced in React v16.3. Context allows components to use shared data without explicitly passing it down as props.

What does React context solve?

As mentioned previously, some types of data are ubiquitous in our application. This example shows a theme used in the App, Button, and Title components:

import React from 'react';

const Title = ({ theme }) => {
  return (
    <h1 style={{ color: theme }}>I am a grey title</h1>
  )
}

export default Title;

In the app.js file:

  • Line 5: We define the gray theme to be used in our application.
  • Line 7: We declare the component App.
  • Line 10-11: The App component has children Title and Button . They are passed theme as props.

In the button.js file:

  • Line 3: We declare the Button component. We get theme from its props using deconstruction.
  • Line 5: We have a button element, and we apply the theme from props to the button's background.

In the title.js file:

  • Line 3: We declare the Title component. We get theme from its props using deconstruction.
  • Line 5: We have an h1 element, and we apply the theme to the header's color.

We can use context to prevent passing theme through props. This can make the code easier to read, understand, and maintain in larger applications.

The React context

There are three steps to create context:

Step 1: Use createContext to make the context object.

We export it so it can be used in other files.

export const ThemeContext = React.createContext();

Step 2: Wrap the context's provider around the components that use the data.

Use its value prop for the shared data. For example, our ThemeContext has a value of gray, which we want to share between the child components Title and Button. Therefore, we wrap those components in ThemeContext.Provider.

const App = () => {
  return (
    <ThemeContext.Provider value="gray">
      <Title />
      <Button />
    </ThemeContext.Provider>
  );
}

Step 3: In the child component(s), consume the context's value prop.

We use ThemeContext.Consumer in the Button and Title components to consume the data that is within ThemeContext.Provider's value prop. The value parameter in lines 4 and 14 correspond to the value prop, defined as "gray". It is applied to the button's background and the h1's color, respectively.

The resulting code no longer needs the theme props.

Whenever the ThemeContext value changes, it will be reflected in Button and Title .

const Button = () => {
  return (
    <ThemeContext.Consumer>
      {value => (
        <button style={{background: value}}>I am a grey button</button>
      )}
    </ThemeContext.Consumer>
  )
}

const Title = () => {
  return (
    <ThemeContext.Consumer>
      {value => (
        <h1 style={{color: value}}>I am a grey title</h1>
      )}
    </ThemeContext.Consumer>
  )
}

Let's put all of this together:

import React from 'react';
import { ThemeContext } from './app';

const Title = () => {
  return (
    <ThemeContext.Consumer>
      {value => (
      <h1 style={{color: value}}>I am a grey title</h1>
      )}
    </ThemeContext.Consumer>
  )
}

export default Title;

In the app.js file:

  • Line 5: We create and export our context object ThemeContext so it can be used in the other components.
  • Line 9: We place the context provider ThemeContext.Provider with its value of "gray" above the component tree that will use the context's data.
  • Lines 10-11: The component tree consists of Title and Button components. Notice how they are not being passed props.

In the button.js file:

  • Line 2: We import ThemeContext from app.js.
  • Line 6: We use the context consumer ThemeContext.Consumer to use the value of ThemeContext.
  • Lines 7-9: The ThemeContext.Consumer 's child must be a function with the value as the parameter. Remember that our value is "gray", which is represented by the value parameter. The function returns a button element, with its background style using the value parameter. Hence, a gray button is rendered in the output.

The title.js follows the same premise as button.js, but instead of returning a button element, it returns an h1 element with its color using the value parameter. Hence, a gray title is rendered in the output.

Note: React also provides a useContext hook as an alternative to the consumer. Read this answer for more information.

RELATED TAGS

react
context

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring