0
0
Reactframework~8 mins

Dependency array usage in React - Performance & Optimization

Choose your learning style9 modes available
Performance: Dependency array usage
HIGH IMPACT
This affects how often React re-runs effects, impacting rendering speed and responsiveness.
Running a side effect only when specific values change
React
useEffect(() => {
  fetchData();
}, [userId]);
Effect runs only when userId changes, reducing unnecessary work and improving responsiveness.
📈 Performance Gaintriggers effect only on dependency change, reducing CPU load and improving INP
Running a side effect only when specific values change
React
useEffect(() => {
  // expensive operation
  fetchData();
});
Effect runs after every render, causing repeated expensive operations and blocking UI updates.
📉 Performance Costtriggers effect on every render, increasing CPU usage and blocking rendering frequently
Performance Comparison
PatternEffect RunsCPU UsageRender BlockingVerdict
No dependency arrayRuns every renderHighBlocks rendering frequently[X] Bad
Empty dependency arrayRuns onceLowMinimal blocking[OK] Good
Correct dependency arrayRuns on relevant changesMinimalMinimal blocking[OK] Good
Rendering Pipeline
React schedules effects after rendering. Dependency arrays control when effects run, affecting CPU work and paint timing.
Commit phase
Effect execution
Paint
⚠️ BottleneckEffect execution causing CPU blocking and delayed paint
Core Web Vital Affected
INP
This affects how often React re-runs effects, impacting rendering speed and responsiveness.
Optimization Tips
1Always specify dependencies to control when effects run.
2Include all variables used inside the effect in the dependency array.
3Avoid empty or missing dependency arrays unless effect should run only once.
Performance Quiz - 3 Questions
Test your performance knowledge
What happens if you omit the dependency array in useEffect?
AEffect runs only once on mount.
BEffect never runs.
CEffect runs after every render, causing potential performance issues.
DEffect runs only when dependencies change.
DevTools: React DevTools Profiler
How to check: Record a profiling session while interacting with the component. Look for frequent effect executions and re-renders.
What to look for: High number of effect calls or re-renders indicates missing or incorrect dependency arrays.