React Js Manage Global Data with Context API Tutorial

React Context API example; React context offers a convenient way to share data globally. The context API is best suited for sharing global: theme state, component state, user settings and many more.

Normally, we pass data from one component to another using props. This strategy is efficient as long as your app size is small. Once the app grows, sharing data between components becomes a little unmanageable.

In this tutorial, we’ll learn how to use Context API in React and manage the global state without using Redux.

We’ll create a functional component and show you how to add and use the useContext hook to manage user state in React.

How to Create and Consume useContext Hook in React

  1. Install New React Project
  2. Create Context
  3. Set Data with Context Provider
  4. Consume Context Data
  5. Run React Server

Install New React Project

Open the terminal, and install a new React app using the CRA tool. Then, enter it into the project folder.

npx create-react-app demo-react-app
cd demo-react-app

We are using bootstrap library for styling the UI components; execute the command to add the package.

npm install bootstrap

Create Context

In order to use context API in React, make the contexts directory with the LoginContext.js file.

import { createContext } from "react";

export const LoginContext = createContext({});

Set Data with Context Provider

Import the LoginContext access the Provider property pass the value object; you can pass any number of properties you want to share globally.

You have to add the given code into the App.js file.

import React, { useState } from "react";
import "bootstrap/dist/css/bootstrap.min.css";

import Login from "./components/Login";
import Profile from "./components/Profile";
import { LoginContext } from "./contexts/LoginContext";

function App() {
  const [user, setUser] = useState(false);
  const [showProfile, setProfile] = useState(false);
  return (
    <div className="container mt-5">
      <LoginContext.Provider value={{ user, setUser, setProfile }}>
        {showProfile ? <Profile /> : <Login />}
      </LoginContext.Provider>
    </div>
  );
}

export default App;

Consume Context Data

We need to make components where we can retrieve the values using Context. In the components/ folder, create a Login.js file and the following code.

import React, { useContext } from "react";
import { LoginContext } from "../contexts/LoginContext";

export default function Login() {
  const { user, setUser, setProfile } = useContext(LoginContext);
  return (
    <>
      <h2 className="mb-2">React Js Context API Example</h2>

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

      <div>
        <input
          type="text"
          className="form-control mb-2"
          placeholder="Enter name"
          onChange={(e) => {
            setUser(e.target.value);
          }}
        />
      </div>
      <button
        className="btn btn-dark"
        type="submit"
        onClick={() => {
          {
            user && setProfile(true);
          }
        }}
      >
        Login
      </button>
    </>
  );
}

Create Profile.js file in components/ directory and add the following code to the file.

import React, { useContext } from "react";
import { LoginContext } from "../contexts/LoginContext";

export default function Profile() {
  const { user } = useContext(LoginContext);
  return (
    <div>
      <div className="mb-3 display-3">{user}</div>
    </div>
  );
}

Run React Server

Let’s start the React server and open the app on the browser using the following command.

npm start
http://localhost:3000

React Js Manage Global Data with Context API Tutorial

Conclusion

The context in React is a great innovation for sending global data in child components. You don’t have to worry about component structure or the components tree.

Sharing data between components consists of three major steps: Building, Sharing and Consuming the context — In this guide, we’ve covered everything.