useEffect: Side Effects
Side effects are anything that affects something outside your component: API calls, timers, subscriptions, DOM manipulation.
Basic useEffect
useEffect(() => {
// This runs after every render
console.log('Component rendered!');
});
Dependency Array
Control when the effect runs:
// Runs after EVERY render
useEffect(() => { });
// Runs ONCE on mount
useEffect(() => { }, []);
// Runs when count changes
useEffect(() => { }, [count]);
// Runs when count OR name changes
useEffect(() => { }, [count, name]);
Cleanup Function
Return a function to clean up:
useEffect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
// Cleanup: runs before next effect or unmount
return () => clearInterval(timer);
}, []);
Common Use Cases
| Use Case | Example |
|---|---|
| Fetch data | API calls on mount |
| Subscriptions | WebSocket connections |
| Event listeners | Window resize, scroll |
| Document title | Update based on state |
| Timers | Intervals, timeouts |
The Mental Model
Think of useEffect as:
- "After render, do this"
- "Before the next effect (or unmount), clean up"
Explore useEffect below!