React.js / React Hooks

Managing Global State with useContext

This tutorial will guide you through the useContext React Hook. You will learn how to manage global state and pass data through components without prop drilling.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces React hooks for functional components to manage state and side effects.

Introduction

In this tutorial, we are going to learn how to manage global state with React's useContext Hook. Managing state in an application can be a challenging task especially when it comes to passing data through components. The useContext Hook provides an easier way to handle this task by allowing you to pass data through the component tree without having to pass props through every level.

What you will learn

  • What is useContext and how it works
  • How to create and use a context
  • How to manage global state

Prerequisites

  • Basic knowledge of JavaScript
  • Familiarity with React and hooks

Step-by-Step Guide

Understanding useContext

React’s useContext Hook is a built-in hook that lets you create global state and access it from anywhere in the component tree, without having to pass the state down through props.

Creating and Using a Context

The first step to using useContext is creating a context. This is done using React.createContext().

const MyContext = React.createContext(defaultValue);

You can now provide this context to part of your app using MyContext.Provider and consume it using MyContext.Consumer or useContext(MyContext).

Code Examples

Creating a Context and a Provider

import React from 'react';

// Create a Context
const NumberContext = React.createContext();

// Create a provider for components to consume and subscribe to changes
export const NumberProvider = props => {
  const [number, setNumber] = React.useState(0);

  return (
    <NumberContext.Provider value={[number, setNumber]}>
      {props.children}
    </NumberContext.Provider>
  );
};

export default NumberContext;

This code creates a context called NumberContext and a provider component NumberProvider. The provider uses the useState hook to create state and provides it to the consuming components.

Consuming the Context

Now let's create a component that will consume this context.

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

const MyComponent = () => {
  const [number, setNumber] = useContext(NumberContext);

  return (
    <div>
      <p>The number is: {number}</p>
      <button onClick={() => setNumber(number + 1)}>Increase</button>
    </div>
  );
};

export default MyComponent;

In this component, we use the useContext hook to consume the NumberContext. We can now access and modify the number state directly from this component.

Summary

In this tutorial, we learned about the useContext Hook and how to use it to manage global state in a React application. We created a context and a provider, then consumed the context using the useContext hook. This method provides a clean and efficient way to manage global state and pass data through components without prop drilling.

Practice Exercises

Exercise 1: Create a context for managing a list of to-do items. Implement functionality for adding and removing items.

Exercise 2: Create a context for managing user authentication state. Implement functionality for logging in and logging out.

For both exercises, remember to create a provider and use the useContext hook to consume the state in your components.

Next Steps

Now that you understand how to use the useContext hook, you can explore more complex state management solutions like Redux or MobX. These libraries provide more advanced features but can be overkill for simpler applications.

Additional Resources

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

File Size Checker

Check the size of uploaded files.

Use tool

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

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