Context · Common pitfalls

1 min read
Mid-level3 min read
Rapid overview

Common pitfalls

Missing Provider

// ❌ Bad - no provider in tree
function App() {
  return <UserProfile />; // Will throw error or get undefined
}

// ✅ Good - provider wraps consumers
function App() {
  return (
    <UserProvider>
      <UserProfile />
    </UserProvider>
  );
}

Not Memoizing Value

// ❌ Bad - causes all consumers to re-render
function Provider({ children }) {
  const [count, setCount] = useState(0);
  return (
    <Context.Provider value={{ count, setCount }}>
      {children}
    </Context.Provider>
  );
}

// ✅ Good - memoized value
function Provider({ children }) {
  const [count, setCount] = useState(0);
  const value = useMemo(() => ({ count, setCount }), [count]);
  return (
    <Context.Provider value={value}>
      {children}
    </Context.Provider>
  );
}

Overusing Context

// ❌ Bad - context for local state
function Form() {
  return (
    <FormContext.Provider value={formState}>
      <FormField name="email" />
      <FormField name="password" />
    </FormContext.Provider>
  );
}

// ✅ Good - props for local state
function Form() {
  const [formState, setFormState] = useState({});
  return (
    <>
      <FormField name="email" value={formState.email} onChange={...} />
      <FormField name="password" value={formState.password} onChange={...} />
    </>
  );
}

See also