Managing Global State with useContext

Tutorial 3 of 5

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