Skip to main content
Albero Academy

Context & Global State

Share data across the tree without prop drilling — createContext, providers, useContext, and how to structure global state.

Chapter 8React15 min readBeginner friendly
  • #React
  • #Context
  • #State

Passing a prop down through many layers just to reach a deep component — prop drilling — is tedious and fragile. React Context lets you provide a value at the top of the tree and read it anywhere below, no matter how deep. It's how themes, the current user and app settings are shared.

The prop-drilling problem

If App has the current user and a button five levels down needs it, you'd thread user through every component in between — even ones that don't use it. Context removes that plumbing.

Creating context

create + provide
import { createContext, useContext, useState } from "react";
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState("light");
const value = { theme, toggle: () => setTheme(t => t === "light" ? "dark" : "light") };
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}

Consuming context

Wrap the app in the provider, then any descendant reads the value with useContext — often via a small custom hook for convenience:

read anywhere
// A convenience hook
export const useTheme = () => useContext(ThemeContext);
// Any component, any depth:
function ThemeToggle() {
const { theme, toggle } = useTheme();
return <button onClick={toggle}>Theme: {theme}</button>;
}

Context + reducer

For real global state, combine Context (to share) with useReducer (to manage) — a lightweight alternative to a state library for many apps:

global state pattern
function AppProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initial);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
}

When (not) to use it

Practice

Build a ThemeProvider with a useTheme hook and a toggle button that works no matter how deeply nested. Then add an AuthContext holding a fake user and a logout, and read it from a header component.

Key takeaways

  1. 01Context shares a value across the tree without prop drilling.
  2. 02createContext + a Provider supply the value; useContext reads it anywhere below.
  3. 03Wrap useContext in a small custom hook (useTheme) for ergonomics.
  4. 04Context + useReducer is a lightweight global-state pattern.
  5. 05Every consumer re-renders on value change — use Context for stable app-wide data, a library for heavy state.