React Js Context API Global State Management Tutorial

In this guide, we will not just talk about React Context api but will share the practical solution regarding how to set up context api in React and manage the global state easily.

React apps are created by connecting many components. It is obvious to share a single state in many components. We take the help of props objects for transferring data between multi-components. This method is good somehow, and it becomes difficult to manage when the application size increases.

We get stuck with a term called prop drilling, like sending data from parent to child or grandparent to child. React also offers a robust solution to tackle the prop drilling issue.

The React Context API pattern is ideally used in React apps. It allows to produce of global variables that can be used in any component, regardless of the component hierarchy.

How to Manage Global State in React with Context API

  • Step 1: Install React Project
  • Step 2: Add Bootstrap Library
  • Step 3: Define Context API
  • Step 4: Create Global State with Context API
  • Step 5: Consume Global State in React
  • Step 6: Run Development Server

Install React Project

Let us begin the first step by installing the new react project using the given command.

npx create-react-app react-context-api-example

Once the app is ready, go inside the project directory.

cd react-context-api-example

Add Bootstrap Library

The bootstrap library is not important from context api context, however it is being used here to speed up the UI design process.

npm install bootstrap

Define Context API

You might have more than one contexts in react app. Therefore, make the seperate contexts/ directory, and also make the new UserContext.js file.

Now, import the createContext module from ‘react’ package, define the UserContext module using createContext() method.

import { createContext } from 'react'

export const UserContext = createContext({})

Create Global State with Context API

We will define the UserContext provider in the global App.js component file. Set the useState, which contains user and setUser values, and define isUserLoggedIn values.

We will add these values to the provider and access these properties in the components.

import React, { useState } from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css'

import Login from './components/Login'
import Dashboard from './components/Dashboard'

import { UserContext } from './contexts/UserContext'

export default function App() {
  const [user, setUser] = useState(false)
  const [isUserLoggedIn, setUserProfile] = useState(false)

  return (
    <div>
      <UserContext.Provider value={{ user, setUser, setUserProfile }}>
        {isUserLoggedIn ? <Dashboard /> : <Login />}
      </UserContext.Provider>
    </div>
  )
}

Consume Global State in React

In the previous step, we created and set up the Context API. Now, we will use the Context in React component.

Create and open the components/Login.js file, import the UserContext and access the context values using the object destructuring method.

import React, { useContext } from 'react'
import { UserContext } from '../contexts/UserContext'

export default function Login() {
  const { user, setUser, setUserProfile } = useContext(UserContext)

  return (
    <>
      <h2 className="mb-4">React Global State Management Example</h2>
      <main className="form-signin">
        <div className="d-flex justify-content-center mb-2">{user}</div>

        <h2 className="mb-2">Login</h2>

        <div className="form-floating">
          <input
            type="text"
            className="form-control mb-2"
            onChange={(e) => {
              setUser(e.target.value)
            }}
          />
          <label>Name</label>
        </div>

        <button
          className="btn btn-dark"
          type="submit"
          onClick={() => {
            {
              user && setUserProfile(true)
            }
          }}
        >
          Login
        </button>
      </main>
    </>
  )
}

Now, we have to make the another Dashboard.js file in components folder make sure to import and use the context api in this file.

import React, { useContext } from 'react'
import { UserContext } from '../contexts/UserContext'

export default function Dashboard() {
  const { user } = useContext(UserContext)

  return (
    <div>
      <div className="mb-3">{user}</div>
    </div>
  )
}

Run Development Server

Head over to terminal, type the command and hit enter.

npm start

You can now test the react app using provided url.

http://localhost:3000

React Js Context API Global State Management Tutorial

Summary

In this guide, we have explained how to use context api in React. We also learned how to gracefully and easily share data among multiple components without passing data through props manually.

React context enables us to store state centrally. We can share that information with any component throughout our react app.

In React, we have many ways to manage a state through a central system, and Redux is one tool that solves a similar problem.

However, it is more advance than Context api. But that doesn’t mean context api is less important than redux both are useful based on the app’s requirement.