How to Use the React useContext Hook

09/27/2021

Contents

In this article, you will learn how to use the React useContext hook.

Using the useContext hook

The React useContext hook is used to consume a context that is created using the React createContext API. It allows components to access the context data without having to pass it down through props. Here are the steps to use the useContext hook:

Create a context object using the createContext API. This should be done in a separate file to keep the context logic isolated from the component code.

import React from 'react';

const MyContext = React.createContext();
export default MyContext;

Wrap the components that need access to the context data in the provider component. This should be done in the parent component that contains all the child components that need access to the context data.

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

function App() {
  const myContextValue = { /* data to be shared */ };
  return (
    <MyContext.Provider value={myContextValue}>
      <ChildComponent1 />
      <ChildComponent2 />
    </MyContext.Provider>
  );
}

Use the useContext hook in the child component to access the context data. This should be done in any child component that needs access to the context data.

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

function ChildComponent1() {
  const myContextValue = useContext(MyContext);
  // use myContextValue in the component
  return (/* component JSX */);
}

The useContext hook takes the context object as its argument and returns the current context value. It is important to note that the context object must be imported into the component before it can be used with the useContext hook.

With these steps, you should be able to use the useContext hook to consume a context in your React application.