Middle+
What is a dependencies array in useEffect? What happens if you pass an empty array or do not pass it at all?
sobes.tech AI
Answer from AI
In React, the useEffect hook takes an array of dependencies as its second argument — a list of values that, when changed, will cause the effect to re-run.
- If you pass an empty array
[], the effect will run only once — after the first render of the component (similar tocomponentDidMount). - If you do not pass a dependencies array at all, the effect will run after every render of the component, which can lead to unwanted repeated calls.
Example:
useEffect(() => {
console.log('Runs only once');
}, []);
useEffect(() => {
console.log('Runs after every render');
});
useEffect(() => {
console.log('Runs when count changes');
}, [count]);
Thus, the dependencies array controls when exactly the effect should trigger, optimizing the component's performance.