useContext

Read context values without passing props through every level.

Syntaxconst theme = useContext(ThemeContext);

useContext lets a component read a value from the nearest matching Context Provider above it, no matter how deep it is. This avoids prop drilling — passing props through many intermediate components that do not use them.

Three steps

  1. Create a context with createContext.
  2. Wrap part of the tree in <MyContext.Provider value={...}>.
  3. Read it anywhere below with useContext(MyContext).

Example

Example · javascript
import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function Button() {
  const theme = useContext(ThemeContext);
  return <button className={theme}>Themed</button>;
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Button />
    </ThemeContext.Provider>
  );
}

When to use it

  • A theme system stores the current colour scheme in a context so any deeply nested component can read the active theme without receiving it through dozens of props.
  • An authentication context exposes the logged-in user to every route so a UserAvatar in the header and a DeleteAccount button in settings both access the same user object.
  • A feature-flag context distributes remote-config values app-wide so feature gates can be checked in any component without API calls at each leaf node.

More examples

Create and provide context

Creates a context with a default value and a provider that supplies both the current theme and a setter.

Example · jsx
import { createContext, useState } from 'react';

export const ThemeContext = createContext('light');

export function ThemeProvider({ children }) {
  const [theme, setTheme] = useState('light');
  return (
    <ThemeContext.Provider value={{ theme, setTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

Consume context with useContext

Reads the theme value from context with useContext so no prop needs to be passed from parent to child.

Example · jsx
import { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';

function ThemedButton({ children }) {
  const { theme } = useContext(ThemeContext);
  return (
    <button className={`btn btn--${theme}`}>
      {children}
    </button>
  );
}

Toggle context value

Reads and writes the context value from a deeply nested component without prop drilling.

Example · jsx
import { useContext } from 'react';
import { ThemeContext } from './ThemeProvider';

function ThemeToggle() {
  const { theme, setTheme } = useContext(ThemeContext);
  return (
    <button onClick={() => setTheme(t => t === 'light' ? 'dark' : 'light')}>
      Switch to {theme === 'light' ? 'dark' : 'light'} mode
    </button>
  );
}

Discussion

  • Be the first to comment on this lesson.