What Is Use Context In React.js

In this article, we will learn how to use useContext hook in React.

useContext: “useContext” hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level.

  • React Context is a way to manage state globally.
  • It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.

Create Context:

To create context, you must Import createContext and initialize it:

import { useState, createContext } from "react";
import ReactDOM from "react-dom/client";

const UserContext = createContext()

Next we’ll use the Context Provider to wrap the tree of components that need the state Context.

Context Provider:

Wrap child components in the Context Provider and supply the state value.

function Component1() {
  const [user, setUser] = useState("Jesse Hall");

  return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 user={user} />
    </UserContext.Provider>
  );
}

The user Context is now accessible to all components in this tree.

Use the useContext Hook

The useContext Hook is required to access the Context in a child component.

First, in the import statement, include the useContext clause

import { useState, createContext, useContext } from "react";

My page will look like this:

import { useState, createContext, useContext } from "react";

const UserContext = createContext();

function App() {
    const [user, setUser] = useState("Marsh mallow");

    return (
        <UserContext.Provider value={user}>
            <h1>{`Hello ${user}!`}</h1>
            <Component2 user={user} />
        </UserContext.Provider>
    );
}

function Component2() {
    return (
        <>
            <h1>Component 2</h1>
            <Component3 />
        </>
    );
}

function Component3() {
    return (
        <>
            <h1>Component 3</h1>
            <Component4 />
        </>
    );
}

function Component4() {
    return (
        <>
            <h1>Component 4</h1>
            <Component5 />
        </>
    );
}

function Component5() {
    const user = useContext(UserContext);

    return (
        <>
            <h1>Component 5</h1>
            <h2>{`Hello ${user} again!`}</h2>
        </>
    );
}

export default App

Output:

Submit a Comment

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

Subscribe

Select Categories