React.js / React Context and Global State

Creating and Providing Context for Components

This tutorial will guide you on how to create and provide context for your React components. We'll start by creating a Context object, and then we'll learn how to use a Provider t…

Tutorial 2 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 the creation and utilization of context in React applications. Context provides a way to pass data through the component tree without having to pass props down manually at every level. It's an essential tool for managing state and helps simplify the flow of data through your application.

What you will learn:
- How to create a Context object
- How to use a Provider to make the Context value available to your components
- How to consume the Context data in your components

Prerequisites:
- Basic knowledge of JavaScript
- Understanding of React and its component-based architecture
- Familiarity with ES6 syntax and features

2. Step-by-Step Guide

Creating a Context Object

To create a Context object, we use React's createContext function, which returns an object with Provider and Consumer components.

import React from 'react';

// Create a Context object
const MyContext = React.createContext(defaultValue);

The defaultValue is optional and will be used if a component does not have a matching Provider above it in the tree.

Providing Context

A Context Provider is a React component that allows consuming components to subscribe to context changes. You can place it anywhere above the components that need to access its value.

<MyContext.Provider value={/* some value */}>

Consuming Context

There are several ways to consume the context data in your components:

  • Using the Consumer component:
<MyContext.Consumer>
  {value => /* render something based on the context value */}
</MyContext.Consumer>
  • Using the useContext Hook:
const value = React.useContext(MyContext);

3. Code Examples

Here is an example of how to create and use context in a simple React app:

import React from 'react';

// Step 1: Create a Context object
const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    // Step 2: Use a Provider to pass the current theme to the tree below
    return (
      <ThemeContext.Provider value="dark">
        <Toolbar />
      </ThemeContext.Provider>
    );
  }
}

// A component in the middle doesn't have to pass the theme down explicitly anymore
function Toolbar() {
  return (
    <div>
      <ThemedButton />
    </div>
  );
}

class ThemedButton extends React.Component {
  // Step 3: Consume the context value
  static contextType = ThemeContext;
  render() {
    return <Button theme={this.context} />;
  }
}

In this example, ThemeContext.Provider provides the current theme to the component tree below it. Then, ThemedButton uses the contextType property to consume the current theme from the context.

4. Summary

In this tutorial, we learned how to create and provide context for React components. We created a Context object, used a Provider to make the Context value available to the component tree, and consumed the Context data in a component.

Next steps for learning:
- Learn more about Context API from the official React documentation
- Practice handling more complex state with Context
- Learn about other state management libraries like Redux or MobX

5. Practice Exercises

Exercise 1: Create a context that provides a user object (with properties name and age) to the component tree. Make a Profile component that consumes this context and displays the user's name and age.

Exercise 2: Expand on the previous exercise. Add a button in the Profile component that, when clicked, increases the user's age by 1.

Solutions:

  1. For the first exercise:
// Create UserContext
const UserContext = React.createContext();

// Provide the context value
<UserContext.Provider value={{ name: 'John', age: 25 }}>
  <Profile />
</UserContext.Provider>

// Consume the context value in Profile component
function Profile() {
  const user = React.useContext(UserContext);
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
    </div>
  );
}
  1. For the second exercise, you can use the useState hook to handle the user's age:
// Inside your component that provides the context value
const [user, setUser] = React.useState({ name: 'John', age: 25 });

// Provide the context value
<UserContext.Provider value={{ user, setUser }}>
  <Profile />
</UserContext.Provider>

// Consume the context value in Profile component and add a button to increase age
function Profile() {
  const { user, setUser } = React.useContext(UserContext);
  const handleAgeIncrease = () => {
    setUser({ ...user, age: user.age + 1 });
  };
  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <button onClick={handleAgeIncrease}>Increase Age</button>
    </div>
  );
}

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

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

Interest/EMI Calculator

Calculate interest and EMI for loans and investments.

Use tool

Percentage Calculator

Easily calculate percentages, discounts, and more.

Use tool

XML Sitemap Generator

Generate XML sitemaps for search engines.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

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