Context: Dependency Injection for the Tree

Context lets a component receive a value from a distant ancestor without passing it through every intermediate component. It is useful for values that are conceptually shared across a subtree, such as theme, locale, authentication context, or feature configuration.

Context is not automatically a global state-management solution. Updating a context value can cause consumers to re-render, and putting rapidly changing large objects into one context can create unnecessary work.

Split contexts by responsibility when needed. A theme context should not necessarily also contain rapidly changing application data.

Theme context
const ThemeContext = createContext("light");

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

function Button() {
  const theme = useContext(ThemeContext);
  return <button data-theme={theme}>Save</button>;
}
💡 Context removes the need for intermediate components to forward the theme prop.
Key Takeaways
  • Context solves tree-wide dependency passing.
  • Context is not automatically a replacement for every state store.
  • Split contexts when update frequency or ownership differs.