useContext

useContext is a React Hook that reads a value from a Context, letting a component access shared data without passing it down through props at every level. It is the consumer side of the Context API.

React

You first create a Context and wrap part of your app in its Provider, giving it a value. Any component inside can then call useContext to read that value directly, no matter how deeply nested it is.

This solves 'prop drilling' — the tedium of threading the same prop through many intermediate components. Context is ideal for app-wide data like the current theme, language, or signed-in user.

Syntax

const value = useContext(MyContext);

Examples

JSX — Button reads 'dark' from the surrounding Provider, so it renders with className 'dark' without receiving a prop.

import { createContext, useContext } from "react";

const ThemeContext = createContext("light");

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

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

Learn it in a lesson

See also

Back to the Dictionary