Thuta Learning
IntermediateWeb Developmentintermediate

useContext Hook

Relax. We'll talk through this in plain words — no textbook voice.

`useContext` lets you share data across a component tree without manually passing props down through every level from parent to child. It's handy for things like theme, language, the logged-in user, or app settings that many child components need.

jsx
import { createContext, useContext } from 'react';

const ThemeContext = createContext('light');

function ThemeLabel() {
  const theme = useContext(ThemeContext);
  return <p>Current theme: {theme}</p>;
}

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

`ThemeContext.Provider` passes the value `dark` down to the component tree below it. `ThemeLabel` grabs that value with `useContext(ThemeContext)` and displays it in the UI.

You should see
The browser shows the text `Current theme: dark`.

Info

When props drilling gets out of hand, Context can clean up your code — but shoving frequently-changing state into context can hurt performance.

Easy traps

  • Use `useContext` without a Provider and all you'll get is the default value passed to `createContext()`.
useContext Hook | Thuta Learning