Common useEffect Patterns
Let's explore practical patterns for using useEffect in real applications. These patterns cover the most common scenarios you'll encounter.
Data Fetching Pattern
The most common use case for useEffect is fetching data:
Loading React playground...
Handling Race Conditions
When userId changes rapidly, we need to ignore stale responses:
Loading React playground...
Document Title Effect
Syncing document title with component state:
Loading React playground...
Window Event Listener Pattern
Adding and cleaning up window event listeners:
Loading React playground...
Local Storage Sync Pattern
Syncing state with localStorage:
Loading React playground...
Debounced Effect Pattern
Debouncing expensive operations:
Loading React playground...
Interval Effect Pattern
Managing intervals with proper cleanup:
Loading React playground...
Exercise: Data Fetching
Loading exercise...
Exercise: Debounced Search
Loading exercise...
Exercise: Window Size Hook
Loading exercise...
Key Takeaways
- Data fetching - Handle loading, data, and error states; watch for race conditions
- Event listeners - Always clean up with removeEventListener on unmount
- Timers - Clear intervals and timeouts in cleanup to prevent memory leaks
- Local storage - Sync state with storage; handle initial read on mount
- Debouncing - Use cleanup to cancel pending operations when deps change
- Race conditions - Use a cancelled flag or AbortController to ignore stale responses

