Skip to main content

Lesson 2 of 9

Context API - Production Patterns

Context API is often misused - for everything from auth to real-time notifications. Understanding its performance characteristics and the context-splitting pattern lets you use it correctly: for low-frequency, truly global values.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Context with useReducer - Auth Pattern

Context with useReducer - Auth Pattern
import { createContext, useContext, useReducer, useMemo, type ReactNode } from 'react';

// Auth state with useReducer - complex enough for reducer
interface AuthState {
  user: User | null;
  isLoading: boolean;
  error: string | null;
}

type AuthAction =
  | { type: 'LOGIN_START' }
  | { type: 'LOGIN_SUCCESS'; payload: User }
  | { type: 'LOGIN_ERROR'; payload: string }
  | { type: 'LOGOUT' };

function authReducer(state: AuthState, action: AuthAction): AuthState {
  switch (action.type) {
    case 'LOGIN_START': return { ...state, isLoading: true, error: null };
    case 'LOGIN_SUCCESS': return { user: action.payload, isLoading: false, error: null };
    case 'LOGIN_ERROR': return { user: null, isLoading: false, error: action.payload };
    case 'LOGOUT': return { user: null, isLoading: false, error: null };
  }
}

// Typed context
interface AuthContextValue {
  state: AuthState;
  login: (credentials: { email: string; password: string }) => Promise<void>;
  logout: () => void;
}

const AuthContext = createContext<AuthContextValue | undefined>(undefined);

export function AuthProvider({ children }: { children: ReactNode }) {
  const [state, dispatch] = useReducer(authReducer, {
    user: null, isLoading: false, error: null,
  });

  // Stable callbacks - won't change between renders
  const login = useMemo(() => async (credentials: { email: string; password: string }) => {
    dispatch({ type: 'LOGIN_START' });
    try {
      const user = await apiLogin(credentials);
      dispatch({ type: 'LOGIN_SUCCESS', payload: user });
    } catch (err) {
      dispatch({ type: 'LOGIN_ERROR', payload: (err as Error).message });
    }
  }, []);

  const logout = useMemo(() => () => {
    apiLogout();
    dispatch({ type: 'LOGOUT' });
  }, []);

  const value = useMemo(() => ({ state, login, logout }), [state, 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 inside AuthProvider');
  return ctx;
}

Common Mistakes - Context

  • No useMemo on context value - a new object is created every render causing all consumers to re-render; always memoize the context value object
  • One giant AppContext - split into AuthContext, ThemeContext, etc., each with focused state to minimize unnecessary re-renders
  • Context for server data - each page that needs users would re-fetch or get stale data; use TanStack Query for all API data
  • Missing Provider - when a component accesses context without a Provider above it, it gets the default value (undefined if not initialized); always throw in the custom hook if context is undefined

Tip

Tip

Practice Context API Production Patterns in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Context API - Production Patterns

Practice Task

Note

Practice Task - (1) Write a working example of Context API Production Patterns from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Context API Production Patterns is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Key Takeaways

  • Context API is often misused - for everything from auth to real-time notifications.
  • No useMemo on context value - a new object is created every render causing all consumers to re-render; always memoize the context value object
  • One giant AppContext - split into AuthContext, ThemeContext, etc., each with focused state to minimize unnecessary re-renders
  • Context for server data - each page that needs users would re-fetch or get stale data; use TanStack Query for all API data

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/9 done