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