Performance: Dependency array usage
This affects how often React re-runs effects, impacting rendering speed and responsiveness.
useEffect(() => {
fetchData();
}, [userId]);useEffect(() => {
// expensive operation
fetchData();
});| Pattern | Effect Runs | CPU Usage | Render Blocking | Verdict |
|---|---|---|---|---|
| No dependency array | Runs every render | High | Blocks rendering frequently | [X] Bad |
| Empty dependency array | Runs once | Low | Minimal blocking | [OK] Good |
| Correct dependency array | Runs on relevant changes | Minimal | Minimal blocking | [OK] Good |
[] in a useEffect hook mean?useEffect hook that runs only once after the component mounts?const [count, setCount] = useState(0);
useEffect(() => {
console.log('Count is', count);
}, [count]);
setCount(1);
setCount(2);useEffect usage?const [count, setCount] = useState(0);
useEffect(() => {
console.log(count);
}, []);useEffect that depends on two props: userId and filter. Which dependency array is correct to ensure the effect runs only when these props change?useEffect(() => {
fetchData(userId, filter);
}, ???);userId and filter inside its callback.userId or filter changes, both must be in the dependency array.Pass the test and this pattern moves unknown