Skip to content

React Context

Overview

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

Create the context

1
2
3
4
5
import { useState, createContext } from "react";
import ReactDOM from "react-dom/client";

// or export it
const NameContext = createContext();

Provider

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function Component1() {
  const [name, setName] = useState("Andres");

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

Use

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { useState, createContext, useContext } from "react";

function Component5() {
  const name = useContext(NameContext);

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

useContext returns the context value for the calling component. It is determined as the value passed to the closest SomeContext.Provider above the calling component in the tree. If there is no such provider, then the returned value will be the defaultValue you have passed to createContext for that context. The returned value is always up-to-date. React automatically re-renders components that read some context if it changes.

Update value in sub component

Create combined context with value and update function.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
function Component1() {
  const [name, setName] = useState("Andres");

  return (
    <NameContext.Provider value={{name, setName}}>
      <h1>{`Hello ${name}!`}</h1>
      <Component2 />
    </NameContext.Provider>
  );
}

Extract both and use set function as needed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import { useState, createContext, useContext } from "react";

function Component5() {
  const {name, setName} = useContext(NameContext);

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

(https://react.dev/reference/react/useContext)[https://react.dev/reference/react/useContext]

When prop drilling grows bigger (hundreds of components), start to look into useReducer hook.