051
LVL 02 — CIRCUIT BREAKER SESSION 051 DAY 51

CONTEXT API

🎫 PIXELCRAFT-039
🔧 Refactor | 🟡 Medium | Priority: 🟠 High

Theme preference, user auth status, and editor settings are passed through 6+ levels of components. Adding a new setting means editing every intermediate component. This is unsustainable.
CONCEPTS.UNLOCKED
🌐
React Context API
Share data across the component tree without prop drilling. Any component at any depth can access context data directly — no passing through intermediate components.
🏗
createContext, Provider, useContext
createContext() creates the container. <Provider> wraps the tree and provides the value. useContext() reads it from any child. Three pieces, one system.
Context vs Props vs External
Props: 1-2 levels deep. Context: shared across many components (theme, auth, settings). External state (Redux): very complex apps with many state slices.
Splitting Contexts
Separate concerns: ThemeContext, AuthContext, EditorContext. A theme change shouldn't re-render components that only use auth. Each context triggers only its consumers.
Performance Caveat
Context changes re-render ALL consumers. Splitting contexts minimizes this. For frequently changing data (slider values), keep state local or use memoization.
🪝
Custom Hook for Context
useEditor() wraps useContext with an error check. If used outside the Provider, throw a helpful error. Clean API for consumers.
HANDS-ON.TASKS
01
Identify the Prop Drilling

Trace theme from App → Layout → Sidebar → Panel → FilterSlider — 5 levels! Layout and Sidebar don't even use theme. They just pass it through.

02
Create ThemeContext
const ThemeContext = createContext({ theme: 'dark', toggleTheme: () => {} }); function ThemeProvider({ children }) { const [theme, setTheme] = useLocalStorage('theme', 'dark'); const toggleTheme = () => setTheme(t => t === 'dark' ? 'light' : 'dark'); return ( <ThemeContext.Provider value={{ theme, toggleTheme }}> <div className={ theme === 'dark' ? 'dark' : '' }> {children} </div> </ThemeContext.Provider> ); } // Any component, at any depth: function FilterSlider() { const { theme } = useContext(ThemeContext); // Use theme directly — no props needed! }
03
Create EditorContext with Reducer
const EditorContext = createContext(null); function EditorProvider({ children }) { const [state, dispatch] = useReducer( editorReducer, initialState ); return ( <EditorContext.Provider value={{ state, dispatch }}> {children} </EditorContext.Provider> ); } // Custom hook for easy access: function useEditor() { const context = useContext(EditorContext); if (!context) throw new Error( 'useEditor must be used within EditorProvider' ); return context; }
04
Create AuthContext
const AuthContext = createContext(null); function AuthProvider({ children }) { const [user, setUser] = useState(null); const login = async (credentials) => { /* ... */ }; const logout = () => { setUser(null); }; return ( <AuthContext.Provider value={{ user, login, logout, isAuthenticated: !!user }}> {children} </AuthContext.Provider> ); }
Preparing for the backend (Phase 3). AuthContext provides user, login, logout, and isAuthenticated to any component that needs it.
05
Refactor App & Verify

Wrap App with providers, remove 20+ prop-drilling instances. Verify: theme toggle works from any component, editor state accessible everywhere.

06
Close the Ticket
git switch -c refactor/PIXELCRAFT-039-context git add src/ git commit -m "Add Theme/Editor/Auth contexts, remove prop drilling (PIXELCRAFT-039)" git push origin refactor/PIXELCRAFT-039-context # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Global state is a fundamental challenge in all complex systems.

React Context is the simplest version of this universal problem.

// Shared state everywhere:

Operating systems  → environment variables,
                     system config
Databases          → shared state accessed
                     by multiple processes
Distributed systems → consensus algorithms
                     (Raft, Paxos)

// You'll encounter increasingly complex
// state-sharing challenges as systems
// grow — from Context to Redux to
// distributed databases.
"Context Architecture"
[A] Create a NotificationContext that manages a stack of toast messages. Any component can dispatch({ type: 'SHOW_TOAST', payload: { message, type } }).
[B] Profile with React DevTools: change theme → which components re-render? Split EditorContext into FilterContext and ToolContext to reduce unnecessary re-renders.
[C] Research Zustand — a lightweight alternative to Context + useReducer. Build the same editor state with Zustand. Compare: API simplicity, performance, boilerplate.
REF.MATERIAL
ARTICLE
React Team
Official guide: when to use Context, creating providers, consuming with useContext, and splitting contexts for performance.
CONTEXTOFFICIALESSENTIAL
VIDEO
Web Dev Simplified
Practical Context walkthrough: creating contexts, providers, consumers, custom hooks, and when Context is the right choice.
CONTEXTPRACTICAL
ARTICLE
React Team
Combining useReducer with Context: the pattern used in Session 50-51. Centralized state accessible from anywhere in the tree.
CONTEXTREDUCEROFFICIAL
VIDEO
Fireship
When to use Context vs Redux vs Zustand vs Jotai. The landscape of state management solutions and their tradeoffs.
STATECOMPARISON
ARTICLE
Kent C. Dodds
Best practices: custom hooks for context, splitting providers, performance pitfalls, and when NOT to use Context.
CONTEXTBEST PRACTICES
// LEAVE EXCITED BECAUSE
Prop drilling eliminated. Any component, anywhere in the tree, can access theme, editor state, or auth. The code is cleaner and components are independent.