Overview
Side effects are operations that reach outside the component function - like fetching data, setting up subscriptions, or interacting with browser APIs. TheuseEffect hook manages these operations in functional components.
useEffect Hook
Execute side effects after render
Dependencies
Control when effects run
Cleanup Functions
Prevent memory leaks and bugs
useCallback
Optimize function dependencies
What Are Side Effects?
Side effects are any operations that affect things outside the component function scope.Common Side Effects
Common Side Effects
- Fetching data from APIs
- Subscribing to events
- Setting timers
- Manipulating the DOM directly
- Reading/writing localStorage
- Logging to console
Why useEffect?
Why useEffect?
Side effects should not run during render because:
- They can cause infinite loops
- They make components impure
- They can trigger unnecessary re-renders
useEffect runs after the component renders, keeping render pure.Basic Syntax
Effect Timing:
- Effect runs after render is committed to screen
- Cleanup runs before next effect or unmount
- Dependencies determine when effect re-runs
Fetching Data with useEffect
Here’s a real example from the course showing geolocation and data fetching:App.jsx
Understanding Dependencies
The dependency array controls when your effect runs.- No Dependencies
- Empty Array
- With Dependencies
Effect runs after every render:
Cleanup Functions
Cleanup functions prevent memory leaks by canceling subscriptions, timers, and other ongoing operations.When Cleanup Runs:
- Before the effect runs again
- When the component unmounts
- This prevents memory leaks and stale operations
The useCallback Hook
When passing functions as dependencies touseEffect, use useCallback to prevent unnecessary effect re-runs.
App.jsx
Why useCallback?
Why useCallback?
Functions are recreated on every render. Without This causes child components and effects depending on it to re-run unnecessarily.
useCallback:useCallback Syntax
useCallback Syntax
Common Patterns
Pattern 1: LocalStorage Sync
Pattern 2: Event Listeners
Pattern 3: Async Data Fetching
Optimizing State Updates
Use functional state updates when new state depends on previous state:Functional Updates Benefits:
- Always uses the latest state value
- Prevents bugs from stale closures
- Required when state update depends on previous value
Common Mistakes
Missing Dependencies
Missing Dependencies
Not Cleaning Up
Not Cleaning Up
Infinite Loops
Infinite Loops
Best Practices
Keep Effects Focused
Each effect should handle one concern. Split into multiple effects if needed.
Always Clean Up
Return cleanup functions for timers, subscriptions, and listeners.
List All Dependencies
Include every value used inside the effect in the dependency array.
Use useCallback
Memoize functions passed as dependencies to prevent unnecessary runs.
Resources
React Docs: useEffect
Official documentation for useEffect
You Might Not Need an Effect
Learn when to avoid useEffect