Curriculum
Course: React
Login

Curriculum

React

Text lesson

The Solution

The solution is to create a context.

Create Context

To create context, you need to import createContext and initialize it.

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

const UserContext = createContext()

Next, use the Context Provider to wrap the component tree that requires access to the state Context.

Context Provider

Wrap the child components in the Context Provider and provide 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>
 );
}

Now, all components within this tree will have access to the user Context.

Use the useContext Hook

To use the Context in a child component, access it with the useContext Hook.

First, import useContext in your component.

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

Then you can access the user Context within any component.

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

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

Full Example

Example:

Here is a complete example demonstrating the use of React Context:

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

const UserContext = createContext();

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

 return (
    <UserContext.Provider value={user}>
      <h1>{`Hello ${user}!`}</h1>
      <Component2 />
    </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>
    </>
 );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Component1 />);