React

How to Handle Global State in React js using Context API

React Js Global state management with createContext hook example; In this tutorial, we will help you learn how to create a global state in React js application using the createContext hook.

React Context API Global state tutorial; Managing state in React is easy; who doesn’t know about the useState hook. Well, when it is about handling a simple state in React, then there is no problem.

However, when you have an extensive application where you have to manage the state globally, then it becomes a little bit excruciating.

We will cover how to set the global state in React’s functional component, not just that, but we will also show you how to send the global state from parent component to child components from scratch.

React Context API is an API that allows you context; it helps you create the object. The Context object sends the current context value to its closest matching provider within the tree of components.

React Js Manage Global State with Context API Example

  • Step 1: Download React App
  • Step 2: Install Bootstrap Module
  • Step 3: Create Context File
  • Step 4: Implement Context on Parent Component
  • Step 5: Create Functional Components
  • Step 6: Start React Application

Download React App

We have to install a new React app to show you the coding example for global state management in React.

Install the app using the create-react-app tool, if app is already downloaded then jump onto the subsequent step.

npx create-react-app react-global-state

Now, you can go inside the application directory.

cd react-global-state

Install Bootstrap Module

We need a Bootstrap module, and it is required only to create the UI components rapidly.

You can execute the suggested command to install the package.

npm install bootstrap

Create Context File

Create contexts/ folder, in this folder create SigninContext.js file and add the following code.

import { createContext } from 'react'

export const SigninContext = createContext({})

To use the context api, import the createContext module from the react library, and make it export the const value as given below.

We are exporting it because we will create the context.provider in another file from where we will send the data from parent to child components in React.

Implement Context on Parent Component

Open the App.js file and insert all the code into the file.

import React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import './App.css'

import Signin from './components/Signin'
import Profile from './components/Profile'

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

function App() {
  const [userName, setUserName] = React.useState(false)
  const [displayProfile, setDisplayProfile] = React.useState(false)

  return (
    <div>
      <SigninContext.Provider
        value={{ userName, setUserName, setDisplayProfile }}
      >
        {displayProfile ? <Profile /> : <Signin />}
      </SigninContext.Provider>
    </div>
  )
}

export default App

The logic is simple and easy; we are checking the userName. If the user is not in the text field, we are showing the Signin component; else showing the Profile component.

In the context provider, we are passing three values, userName, setUserName, and setDisplayProfile. We can access these values in the child components using the useContext API.

Create Functional Components

In the src/ directory, you have to create the components/ folder within this folder:

Create the Signin.js file and insert the following code:

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

function Signin() {
  const { userName, setUserName, setDisplayProfile } = useContext(SigninContext)

  return (
    <>
      <h2 className="mb-3 text-center">
        React Js Context API Send Data Parent to Child Component Example
      </h2>
      <main className="form-signin">
        <div className="d-flex justify-content-center mb-3">{userName}</div>

        <h2 className="h3 mb-3 fw-normal">Please sign in</h2>

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

        <button
          className="w-100 btn btn-lg btn-primary"
          type="submit"
          onClick={() => {
            {
              userName && setDisplayProfile(true)
            }
          }}
        >
          Sign in
        </button>
      </main>
    </>
  )
}

export default Signin

Create the Profile.js file and insert the following code:

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

function Profile() {
  const { userName } = useContext(SigninContext)

  return (
    <div>
      <div className="d-flex justify-content-center mb-3 display-2">
        {userName}
      </div>
    </div>
  )
}

export default Profile

To use the context import, useContext named module, or you may directly access it using the React.useContext() approach.

In the context object, we can de-structure the userName, setUserName, and setDisplayProfile properties. We can use these properties to get and set the properties using the context api in react.

Start React Application

We have successfully written the code for setting up the Global State in React.

Now, we need to run the given command for starting the React app.

npm start

Open the browser, copy the mentioned below url, paste it on the browser’s address bar and hit enter to view the app.

http://localhost:3000

Conclusion

In this tutorial, we created a Signin and Profile components; a user can only access the Profile component when the user is signed-in.

We will send the data globally to the profile component from the Signin component (user name) using the context provider api. You have learned how to set the context provider object in React.

Not just that but also learned how to manage the useState hook using the createContext in React. You can now easily access the context provider values, properties and events and send the data or values from parent components to the child components.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.

Recent Posts

How to Add Active Class in Map Items in React Js

In this quick tutorial, we will show you how to quite easily add the active…

2 days ago

How to Create and Use Redux Store in React Js

In this tutorial, we will learn how to create a Redux Store in React application.…

5 days ago

How to Build Dynamic Load More Feature in React Js

This detailed guide will cover how to create the Load More button and display data…

1 week ago

How to Integrate Redux Persist to React Redux Store

In this tutorial, we will step by step learn how to configure redux persist in…

2 weeks ago

React Redux Save Data in Local Storage with Persist Tutorial

In this comprehensive tutorial, we will learn how to persist redux store's states in React…

2 weeks ago

React Js Tailwind CSS Add Light and Dark Mode Toggler Tutorial

In this guide, we are going to learn how to add dark mode and light…

2 weeks ago