How to Use the React Context API in Your Projects

The React Context API is a way to share data between components in a React application, without having to pass the data down through multiple levels of props. Today we will know how we can use the Context API in our projects step by step.

So let's get started-

Table of Contents

  1. Create a Context Object
  2. Wrap Components with a Provider
  3. Consume the Context

Create a Context Object

First, we create a new Context object using the createContext function. This object will hold the shared data that we want to pass between our components. 

We create a new file named MyContext.jsx in the src folder and add the following code to create a context object:

MyContext.jsx
import { createContext } from 'react';

export const MyContext = createContext("");

The code snippet imports the createContext function from the React library and uses it to create a new context object named "MyContext". The context object is then exported to make it available for use in other parts of the application.

Wrap Components with a Provider

After creating a context object, it is necessary to enclose the components that require access to the shared data within a Provider component. The Provider component has a "value" prop that takes in the shared data, and any child component of the Provider can retrieve the shared data.
It is important to bear in mind that the Provider component must be wrapped around the highest-level component in an application to ensure that all descendant components have access to the shared data.

For example:

App.jsx
// Create a parent component that wraps child components with a Provider

import { useState, React } from "react";
import { MyContext } from "./MyContext";
import MyComponent from "./MyComponent";

function App() {
  const [text, setText] = useState("");

  return (
    <div>
      <MyContext.Provider value={{ text, setText }}>
        <MyComponent />
      </MyContext.Provider>
    </div>
  );
}

export default App;

In the given example, there is a parent component named App. It possesses a state variable named text, which is initialized as an empty string. Additionally, a function named setText is defined to modify the value of the text state variable.

Consume the Context

After creating the Provider component, now we will consume the context in other components. To do this, we use the useContext hook from React.

MyComponent.jsx
import { useContext } from 'react';
import { MyContext } from './MyContext';

function MyComponent() {
  const { text, setText } = useContext(MyContext);

  return (
    <div>
      <h1>{text}</h1>
      <button onClick={() => setText('Hello, world!')}>
        Click me
      </button>
    </div>
  );
}

export default MyComponent;

In this example, we've used the useContext hook to access the text and setText variables that were defined in the provider component.

Inside the return statement of MyComponent we've rendered a paragraph element that displays the value of text. We've also rendered a button that, when clicked, will call the setText function to update the value of text to "Hello, world!".

That's it! With these three steps, we can easily share data between components in our React application using the Context API. Just make sure that the components that need to access the shared data are wrapped by the Provider component.