How to Implement React Context API in Just 3 Steps

Looking to set up your global state in React.js without installing any third-party packages? The ideal solution is to use the built-in state management system.

Many companies use context API to manage complex states, some of the famous ones include Facebook, Netflix, Airbnb, Uber, Discord, and so on.

We also use it for authentication state, theme state, language state, global data fetching state, and much more.

In this post, I will run you through our three-step process to implementing React Context API using the best practices.

Content

Prerequisites

Before hopping to our tutorial first set up our environment. Nowadays we usually create our react app using Vite, because it has fast server starting time and out-of-the-box support for TypeScript.

npm create vite@latest 
create react vite

Chose react to start your project, then:

npm install

Step #1 – Create Your Context

We are going to use the best practices for folder structures and optimized performance so let’s first create a folder called contexts to put all of our contexts in the src folder. After that create a file in the context folder called UserInfoContext.jsx.

Open UserInfoContext.jsx

Let’s import createContext from react and create our context:

import { createContext } from "react";

export const UserInfo = createContext(null);

Step #2 – Implement the Context Provider and Add it to the Top Layer

In the previous step, we created our context. Now let’s make our context available to inside every component using a wrapper component.

In the same file as the previous step, create a function called UserInfoContextProvider. This function takes the app.js component or other top-level component in order to make it available for the sub-components in that parent component. The function contains the state that will be shared between the sub-components.

Add UserInfo.Provider component to store the values that are going to be accessible in the UserInfo Context

import { useState, createContext } from "react";

export const UserInfo = createContext(null);

export const UserInfoContextProvider = ({ children }) => {
  const [userInfo, setUserInfo] = useState({
    name: "example",
    email: "example@gmail.com",
  });
  return (
    <UserInfo.Provider value={{ userInfo, setUserInfo }}>
      {children}
    </UserInfo.Provider>
  );
};

Let’s import UserInfoContextProvider and wrap a top layer component:

import UserProfile from "./components/UserProfile";
import { UserInfoContextProvider } from "./contexts/UserInfoContext";

function App() {
  return (
    <UserInfoContextProvider>
      <UserProfile />
    </UserInfoContextProvider>
  );
}

export default App;

Step #3 – Use useContext to access the global state from any components

Now that we have created our context and made it available in any sub-component inside the top layer component, the only step left for us is to access the context using the built-in react hook called useContext.

Import useContext form react and add the context UserInfo from UserInfoContext and put it inside the useContext hook, then we can get the state values that are inserted into the wrapper component by destructuring the object that is returned from the useContext.

import { useContext } from "react";
import { UserInfo } from "../contexts/UserInfoContext";

export default function UserProfile() {
  const { userInfo, setUserInfo } = useContext(UserInfo);
  return (
    <div>
      <p>{userInfo.name}</p>
      <p>{userInfo.email}</p>e
      <button
        onClick={() =>
          setUserInfo({ name: "changed", email: "changed@gmail.com" })
        }
      >
        change name
      </button>
    </div>
  );
}

And that it, We have successfully Implemented React Context API in Just 3 Steps, l hope you found the tutorial useful. Contact us for any

For additional information, you can go to react official docs – react.dev.

Leave a Reply

Your email address will not be published. Required fields are marked *