TExcelTAD
Home › React › React useContext

React useContext

Passing props works well for a few levels, but some data is needed almost everywhere: the current user, the colour theme, the language. Threading such values through every component in between — prop drilling — gets tedious. Context lets a parent make a value available to its whole subtree, and any component below can read it with useContext.

Three steps

jsx
// 1. Create a context (with a default value)
const ThemeContext = createContext('light');

// 2. Provide a value somewhere up the tree
<ThemeContext value="dark">
  <Page />
</ThemeContext>

// 3. Read it anywhere below
const theme = useContext(ThemeContext);

Note: In React 19 you render the context itself as the provider: <ThemeContext value=…>. Older code writes <ThemeContext.Provider value=…>, which still works.

A theme example

jsx · try it yourself
import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

const COLORS = {
  light: { bg: '#ffffff', fg: '#1f2328', border: '#d0d7de' },
  dark: { bg: '#0d1117', fg: '#e6edf3', border: '#30363d' },
};

function Button({ children, onClick }) {
  const theme = useContext(ThemeContext);
  const c = COLORS[theme];
  return (
    <button onClick={onClick} style={{ background: c.bg, color: c.fg, border: `1px solid ${c.border}`, padding: '6px 12px', borderRadius: 6 }}>
      {children}
    </button>
  );
}

function Panel({ title, children }) {
  const theme = useContext(ThemeContext);
  const c = COLORS[theme];
  return (
    <section style={{ background: c.bg, color: c.fg, border: `1px solid ${c.border}`, padding: 12, borderRadius: 8, marginBottom: 8, width: 300 }}>
      <h3 style={{ marginTop: 0 }}>{title}</h3>
      {children}
    </section>
  );
}

function Toolbar() {
  // Toolbar doesn't know about the theme at all
  return (
    <Panel title="Toolbar">
      <Button onClick={() => console.log('saved')}>Save</Button>{' '}
      <Button onClick={() => console.log('shared')}>Share</Button>
    </Panel>
  );
}

export default function App() {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext value={theme}>
      <Toolbar />
      <label>
        <input type="checkbox" checked={theme === 'dark'} onChange={(e) => setTheme(e.target.checked ? 'dark' : 'light')} /> Dark mode
      </label>
    </ThemeContext>
  );
}

Toolbar never passes theme down, yet Panel and Button read it. When App changes the value, every component that uses the context re-renders.

Providing state and actions

A context value can be anything — often an object that holds state and functions to change it:

jsx · try it yourself
import { createContext, useContext, useState } from 'react';

const AuthContext = createContext(null);

function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const login = (name) => setUser({ name, role: name === 'admin' ? 'Administrator' : 'Member' });
  const logout = () => setUser(null);
  return <AuthContext value={{ user, login, logout }}>{children}</AuthContext>;
}

function useAuth() {
  const ctx = useContext(AuthContext);
  if (!ctx) throw new Error('useAuth must be used inside <AuthProvider>');
  return ctx;
}

function Header() {
  const { user, logout } = useAuth();
  return (
    <header style={{ display: 'flex', justifyContent: 'space-between', background: '#eef', padding: 8, width: 340 }}>
      <strong>MyApp</strong>
      {user ? <span>👤 {user.name} <button onClick={logout}>Log out</button></span> : <span>Guest</span>}
    </header>
  );
}

function LoginForm() {
  const { user, login } = useAuth();
  const [name, setName] = useState('');
  if (user) return <p>Welcome, {user.name}! Role: {user.role}</p>;
  return (
    <form onSubmit={(e) => { e.preventDefault(); if (name) login(name); }}>
      <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Try 'admin' or any name" />
      <button>Log in</button>
    </form>
  );
}

export default function App() {
  return (
    <AuthProvider>
      <Header />
      <LoginForm />
    </AuthProvider>
  );
}

Two good habits appear here:

  • A provider component (AuthProvider) owns the state and keeps App clean.
  • A small custom hook (useAuth) wraps useContext and gives a clear error when the provider is missing.

Nearest provider wins

useContext reads the value from the closest provider above the component. Providers can be nested to override a value for one part of the tree:

jsx · try it yourself
import { createContext, useContext } from 'react';

const LevelContext = createContext(1);

function Heading({ children }) {
  const level = useContext(LevelContext);
  const sizes = { 1: 28, 2: 22, 3: 18, 4: 15 };
  return <div style={{ fontSize: sizes[level] ?? 14, fontWeight: 'bold', marginLeft: (level - 1) * 16 }}>H{level}: {children}</div>;
}

function Section({ children }) {
  const level = useContext(LevelContext);
  return <LevelContext value={level + 1}>{children}</LevelContext>;
}

export default function App() {
  return (
    <div>
      <Heading>Cookbook</Heading>
      <Section>
        <Heading>Soups</Heading>
        <Section>
          <Heading>Pho</Heading>
          <Heading>Bun bo Hue</Heading>
        </Section>
        <Heading>Desserts</Heading>
      </Section>
    </div>
  );
}

Each Section reads the current level and provides level + 1 to its children, so headings size themselves automatically.

When to use context

Good fit Probably not
theme, language, current user data used by one or two children — pass props
app-wide settings frequently changing values used by many components (e.g. mouse position)
state shared by a deep subtree as a replacement for good component structure

Tip: Before reaching for context, try passing JSX as children (see Composition). It often removes prop drilling without any new concepts.

If no provider is found, useContext returns the default value passed to createContext.

Test yourself

What does useContext(ThemeContext) return?

  1. The default value always
  2. The value of the nearest ThemeContext provider above the component
  3. The value of the topmost provider
  4. A setter function

How do you provide a context value in React 19?

  1. <ThemeContext value="dark">…</ThemeContext>
  2. ThemeContext.set('dark')
  3. useContext(ThemeContext, 'dark')
  4. <Provider context={ThemeContext}>

What problem does context mainly solve?

  1. Slow rendering
  2. Passing the same props through many intermediate components
  3. Fetching data
  4. Styling components