Back to Course

Learn React

0% Complete
0/0 Steps
Lesson 20 of 32
In Progress

Creating and Consuming Context in React

In the previous lesson, we learned how to create a context object in React using the createContext function. In this lesson, we will learn how to consume context in a React component.

Consuming Context in a Functional Component

To consume context in a functional component, we use the useContext hook. The useContext hook takes in a context object as an argument and returns the current context value.

For example, let’s say we have a context object for storing a user’s theme preference (light or dark). We can consume this context in a functional component like this:

import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

function MyComponent() {
  const { theme } = useContext(ThemeContext);
  return <div>{theme}</div>;
}

In the example above, we use the useContext hook to retrieve the theme from the ThemeContext object. We then use the theme value to render the theme in the component.

Consuming Context in a Class-Based Component

To consume context in a class-based component, we use the static contextType property. The contextType property is a way to consume the nearest current value of a context object in a class component.

For example, let’s say we have a context object for storing a user’s theme preference (light or dark). We can consume this context in a class-based component like this:

import { ThemeContext } from './ThemeContext';

class MyComponent extends React.Component {
  static contextType = ThemeContext;

  render() {
    return <div>{this.context.theme}</div>;
  }
}

In the example above, we use the static contextType property to consume the theme from the ThemeContext object. We then use the theme value to render the theme in the component.

Using Context in a Component Tree

In order for a component to be able to consume context, the component must be a descendant of a component that provides the context.

For example, let’s say we have a context object for storing a user’s theme preference (light or dark). We can provide this context in a component tree like this:

import { ThemeContext } from './ThemeContext';

function App() {
  return (
    <ThemeContext.Provider value={{ theme: 'light' }}>
      <MyComponent />
    </ThemeContext.Provider>
  );
}

In the example above, we use the Context.Provider component to provide the theme context to the MyComponent component. The MyComponent component can then consume the theme context using the useContext hook or the static contextType property.

Conclusion

In this lesson, we learned how to consume context in a functional component using the useContext hook and in a class-based component using the static contextType property. We also learned how to provide context in a component tree using the Context.Provider component. Understanding how to use context in React is a powerful tool for managing state in a React application.

Exercises

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

Create a context object called “LanguageContext” that stores the language preference of a user (e.g. English, Spanish, French). Use the createContext function to create the context object.

import { createContext } from 'react';

const LanguageContext = createContext();

Create a functional component called “LanguageSelector” that allows a user to select their language preference from a dropdown menu. Use the useContext hook to consume the LanguageContext in the component and update the language preference when a new option is selected.

import { useContext } from 'react';
import { LanguageContext } from './LanguageContext';

function LanguageSelector() {
  const { language, setLanguage } = useContext(LanguageContext);

  const handleChange = (event) => {
    setLanguage(event.target.value);
  }

  return (
    <select value={language} onChange={handleChange}>
      <option value="english">English</option>
      <option value="spanish">Spanish</option>
      <option value="french">French</option>
    </select>
  );
}

Create a class-based component called “LanguageDisplay” that displays the current language preference in the LanguageContext. Use the static contextType property to consume the LanguageContext in the component.

import { LanguageContext } from './LanguageContext';

class LanguageDisplay extends React.Component {
  static contextType = LanguageContext;

  render() {
    return <div>{this.context.language}</div>;
  }
}

Create a component called “App” that provides the LanguageContext to the LanguageSelector and LanguageDisplay components. Use the Context.Provider component to provide the context.

import { LanguageContext } from './LanguageContext';

class App extends React.Component {
  state = {
    language: 'english',
  };

  setLanguage = (language) => {
    this.setState({ language });
  }

  render() {
    return (
      <LanguageContext.Provider value={{ language: this.state.language, setLanguage: this.setLanguage }}>
        <LanguageSelector />
        <LanguageDisplay />
      </LanguageContext.Provider>
    );
  }
}

Create a component called “Home” that consumes the LanguageContext and displays a welcome message in the selected language. Use the useContext hook to consume the LanguageContext in the component.

import { useContext } from 'react';
import { LanguageContext } from './LanguageContext';

function Home() {
  const { language } = useContext(LanguageContext);

  let welcomeMessage;
  if (language === 'english') {
    welcomeMessage = 'Welcome';
  } else if (language === 'spanish') {
    welcomeMessage = 'Bienvenido';
  } else if (language === 'french') {
    welcomeMessage = 'Bienvenue';
  }

  return <div>{welcomeMessage}</div>;
}