Category: react
What Is the useEffect Dependency Array?
Published on 27 Oct 2026
Explanation
The dependency array tells React when an effect should run again. An empty array runs the effect after the component mounts, while dependencies make it rerun when their values change.
Code:
import { useEffect } from 'react';
useEffect(() => {
console.log('Runs after every render');
});
useEffect(() => {
console.log('Runs after mount');
}, []);
useEffect(() => {
console.log('Runs when userId changes');
}, [userId]);
Explanation
Without a dependency array, the effect runs after every committed render. With an empty array, it runs after the initial mount, with an extra setup-and-cleanup cycle possible in development Strict Mode.
Code:
useEffect(() => {
console.log('Every committed render');
});
useEffect(() => {
console.log('Mount effect');
}, []);
Explanation
List every reactive value used by an effect in its dependency array. React compares each dependency with its previous value using Object.is.
Code:
useEffect(() => {
document.title = `${firstName} ${lastName}`;
}, [firstName, lastName]);
Explanation
Objects and functions created during rendering get new identities on each render. If they appear in the dependency array, the effect can rerun even when their contents look unchanged.
Code:
const options = { roomId };
useEffect(() => {
connect(options);
return () => disconnect(options);
}, [options]); // New object on each render
Explanation
Do not silence dependency warnings just to stop an effect from rerunning. Restructure the effect, move constants outside the component, or create objects inside the effect so dependencies accurately represent what it uses.
Code:
useEffect(() => {
const options = { roomId };
const connection = connect(options);
return () => connection.disconnect();
}, [roomId]);