Trivia Questions1 min readPremium

React Context and the Provider Pattern

Context lets a component pass a value to any descendant without threading props through every level. The Provider pattern wraps that mechanism in a reusable component plus a custom hook. React Context is documented in createContext and useContext.

1. The three pieces

const ThemeContext = createContext('light');          // 1. create (with a default)

<ThemeContext.Provider value="dark">                 // 2. provide
  <App />
</ThemeContext.Provider>

const theme = useContext(ThemeContext);               // 3. consume

useContext returns the value from the nearest Provider above the component. With no Provider above it, it returns the default passed to createContext.

2. What React Context Is (and Isn’t)

  • It is a dependency injection mechanism, not a state manager. The state still lives in some component (usually the Provider) via useState or useReducer.
  • It solves prop drilling for values many components need: theme, locale, current user, a service client.

3. A production-style provider

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const login = useCallback(async (creds) => setUser(await api.login(creds)), []);
  const logout = useCallback(() => setUser(null), []);

  const value = useMemo(() => ({ user, login, logout }), [user, login, logout]);
  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}

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

Why each detail matters:

  • Default of null + throwing hook: a missing Provider fails loudly instead of silently returning a fake default.
  • useMemo on the value: without it, a new object is created on every Provider render, which re-renders every consumer.
  • Custom hook: consumers never import the raw context, so the implementation can change freely.

4. Re-render behavior

When the Provider’s value changes (by Object.is), every component that consumes that context re-renders, even if it only reads one field that did not change. React.memo on a consumer does not stop this, because context updates bypass props.

5. Provider composition

Apps typically stack providers at the root:

<AuthProvider>
  <ThemeProvider>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </ThemeProvider>
</AuthProvider>

Order matters when one provider consumes another (for example, a provider that calls useAuth() must sit inside AuthProvider).

6. When not to use Context

  • Rapidly changing values read by many components (mouse position, scroll offset). Every change re-renders all consumers.
  • Values used by just one or two levels. Plain props are simpler and more explicit.
  • Server data. A query cache handles caching and invalidation better.