Facebook PixelReact useContext | React JS Tutorial | CodeWithHarry

React useContext

useState is a Hook that lets you add React state to function components. useContext helps to manage states globally, i.e., between components.

Problem

Suppose there is a button in <Navbar /> Component which affects something in <Home /> Component. Problems:

In this case, state can't be held in <Navbar /> or <Home />, it will be in App.js.

To access it, we have to pass it like a prop to the components, and if the component is within 3-4 components, we have to pass it to everyone as shown in the image below:

React Component Hierarchy

Solution - Create Context

It's a hook so first we need to import it from react and initialize it! To do this, write:

import { createContext } from "react";
 
const StateContext = createContext();

Context Provider

Now we need to wrap the component tree that needs the state Context in a Provider. It's like the Provider will provide the state to every component in that tree which is wrapped in Provider.

function App() {
  const [state, setState] = useState('true');
 
  return (
    <StateContext.Provider value={state}>
      <h1>{`Hi! My state is ${state}!`}</h1>
      <Home state={state} />
    </StateContext.Provider>
  );
}

useContext hook

First, we need to import it:

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

To access useContext, you can do something like this:

function Home() {
  const state = useContext(StateContext);
 
  return (
    <>
      <h2>{`Hii! My state is ${state}! `}</h2>
    </>
  );
}