043
LVL 02 — CIRCUIT BREAKER SESSION 043 DAY 43

USE EFFECT

🎫 PIXELCRAFT-031
🐛 Bug | 🟡 Medium | Priority: 🔴 Critical

Canvas shows the original image but doesn't redraw when filter sliders change. Need to sync canvas with React state.
CONCEPTS.UNLOCKED
useEffect
Running code when state changes or component mounts. The bridge between React's declarative world and the imperative outside world (DOM, APIs, timers, localStorage).
[ ]
Dependency Array
[] = run once on mount. [x] = run when x changes. No array = run every render. The dependency array controls WHEN the effect fires.
🧹
Cleanup Functions
Return a function from useEffect to clean up: remove event listeners, cancel timers, abort fetches. Prevents memory leaks and stale handlers.
📌
useRef
Accessing DOM elements in React. const canvasRef = useRef(null) + <canvas ref={canvasRef} />. canvasRef.current gives you the actual DOM element for Canvas API calls.
🔗
Imperative + Declarative
Connecting imperative code (Canvas API: ctx.drawImage, ctx.putImageData) with declarative React. useEffect and useRef are the bridges between these two worlds.
Infinite Loop Debugging
Wrong dependency → effect runs → updates state → triggers effect → updates state → infinite loop. Understanding dependencies prevents this common React bug.
HANDS-ON.TASKS
01
Access the Canvas with useRef
function CanvasArea({ image, filters }) { const canvasRef = useRef(null); useEffect(() => { if (!image || !canvasRef.current) return; const ctx = canvasRef.current.getContext('2d'); // Redraw with filters applied drawWithFilters(ctx, image, filters); }, [image, filters]); // Rerun when image or filters change return <canvas ref={canvasRef} />; }
The dependency array [image, filters] means: rerun this effect whenever image or filters change. When a slider moves → filters state updates → useEffect fires → canvas redraws.
02
Load Preferences on Mount
useEffect(() => { const saved = localStorage.getItem('settings'); if (saved) setSettings(JSON.parse(saved)); }, []); // Empty array = run once on mount
The empty dependency array [] means this effect runs exactly once — when the component first appears. Perfect for loading saved data, initializing resources, or fetching initial data.
03
Keyboard Shortcuts with Cleanup
useEffect(() => { const handleKey = (e) => { if (e.ctrlKey && e.key === 'z') undo(); }; window.addEventListener('keydown', handleKey); return () => window.removeEventListener( 'keydown', handleKey ); // Cleanup! }, []);
The return function is the cleanup. When the component unmounts (or before the effect re-runs), React calls the cleanup to remove the old listener. Without this → memory leak.
04
Debug an Infinite Loop

A wrong dependency triggers an infinite re-render: effect runs → updates state → triggers effect → updates state → crashes.

Identify and fix the incorrect dependency to break the loop.

05
Close the Ticket
git switch -c bugfix/PIXELCRAFT-031-canvas-sync git add src/components/ git commit -m "Sync canvas with React state via useEffect + useRef (PIXELCRAFT-031)" git push origin bugfix/PIXELCRAFT-031-canvas-sync # PR → Review → Merge → Close ticket ✅
CS.DEEP-DIVE

Side effects vs pure computation.

Pure functions produce the same output for the same input. Side effects (DOM updates, network calls, localStorage) are necessary but harder to manage. useEffect is React's designated boundary.

// Pure/impure separation everywhere:

Haskell         → IO monad separates
                   pure from impure
Databases       → reads are pure,
                   writes are side effects
Testing         → pure functions are
                   trivially testable
React           → components are pure,
                   useEffect handles the rest
"Effects Lab"
[A] Add auto-save: whenever filterValues changes, save to localStorage using useEffect. Restore on mount. The app should remember settings across refreshes.
[B] Add a window resize listener that updates canvas dimensions. Include the cleanup function. Test: resize the window → canvas adjusts, unmount → no memory leak.
[C] Create 3 useEffect hooks with different dependency arrays: [] (mount only), [value] (when value changes), no array (every render). Add console.logs to each and observe when they fire.
REF.MATERIAL
ARTICLE
React Team
The official useEffect guide: when you need effects, dependency arrays, cleanup, and common patterns. The definitive resource.
useEffectOFFICIALESSENTIAL
VIDEO
Web Dev Simplified
Practical useEffect walkthrough: dependency arrays, cleanup functions, fetching data, and the most common mistakes.
useEffectPRACTICAL
ARTICLE
React Team
useRef explained: accessing DOM elements, storing mutable values that don't trigger re-renders, and ref vs state.
useRefOFFICIAL
ARTICLE
React Team
When NOT to use useEffect: computed values, event handlers, and transformations that belong in the render. Prevents overuse of effects.
useEffectBEST PRACTICES
VIDEO
Codevolution
Accessing DOM elements, storing previous values, and understanding when useRef is the right choice over useState.
useRefPRACTICAL
// LEAVE EXCITED BECAUSE
Change a filter slider → canvas updates automatically. No manual DOM syncing. React and the Canvas API work together seamlessly.