React.js / React Context and Global State

Consuming Context in Functional and Class Components

In this tutorial, we will learn how to consume context in both functional and class components in React. We'll also compare the different ways of consuming context in these two ty…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Covers using React Context API to manage global state and avoid prop drilling.

1. Introduction

In this tutorial, we will explore how to consume context in React using both functional and class components.

By the end of this tutorial, you will be able to:
- Understand what context is and how to use it
- Consume context in functional components using the useContext hook
- Consume context in class components using the Context.Consumer component

Prerequisites:
- Basic understanding of React
- Knowledge of JavaScript ES6 syntax
- Familiarity with both functional and class components in React

2. Step-by-Step Guide

Context provides a way to pass data through the component tree without having to pass props down manually at every level. In other words, it's a more efficient way to share values between components.

In functional components, we use the useContext Hook to consume context, whereas in class components, we use the Context.Consumer component.

Functional Components

The useContext Hook accepts a context object (the value returned from React.createContext) and returns the current context value, as given by the nearest context Provider up the tree from this component.

Example:

import React, { useContext } from 'react';
import MyContext from './MyContext';

function MyComponent() {
  const contextValue = useContext(MyContext);

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

In this example, MyComponent uses the useContext hook to consume the context value from MyContext.

Class Components

In class components, we can consume context using the <Context.Consumer> component. This lets you subscribe to a context within a function component.

Example:

import React from 'react';
import MyContext from './MyContext';

class MyComponent extends React.Component {
  render() {
    return (
      <MyContext.Consumer>
        {contextValue => <div>{contextValue}</div>}
      </MyContext.Consumer>
    );
  }
}

In this example, MyComponent is a class component that uses the MyContext.Consumer component to consume the context value.

3. Code Examples

Functional Component Example

import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);
  return <button theme={theme}>I am styled by theme context!</button>;
}

In this example, the useContext hook is used to consume the ThemeContext. The value of the context is then used as a prop for the button component.

Class Component Example

import React from 'react';
const ThemeContext = React.createContext('light');

class ThemedButton extends React.Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {theme => <button theme={theme}>I am styled by theme context!</button>}
      </ThemeContext.Consumer>
    );
  }
}

In this example, ThemeContext.Consumer is used to consume the ThemeContext. The value of the context is then used as a prop for the button component.

4. Summary

In this tutorial, we've learned how to consume context in functional and class components in React. We learned that functional components use the useContext hook, while class components use the Context.Consumer component.

The next step in your learning could be understanding when to use context and when to use state or props in your components.

5. Practice Exercises

  1. Create a context and consume it in a functional component.
  2. Create a context and consume it in a class component.
  3. Create a context with multiple values and consume it in a functional component.

Solutions and explanations will be provided after you've attempted these exercises.

Remember, practice is key to mastering any concept. Keep experimenting with different scenarios and use cases.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help