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
Prerequisites
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.
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)
.
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.
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.
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.
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.
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.