By default, a useEffect hook runs after every render. However, in many cases, you may want to control when it runs. You can achieve this by using its optional second argument: the dependency array.
By the end of this reading, you should be able to:
A useEffect hook always runs after the initial render. If a dependency array is provided, the hook will run again only when one of its dependencies changes.
Example:
useEffect(() => {
console.log(num);
}, [num]);
React uses Object.is() to determine if elements in the array have changed.
Consider the following component:
function App() {
const [num, setNum] = useState(0);
useEffect(() => {
console.log("App has rendered");
});
return (
<>
Number: {num}
>
);
}
Each time the button is clicked, num updates, triggering a re-render and causing the useEffect to log a message.
If an effect has no dependencies, an empty array ([]) ensures it runs only once after the first render:
useEffect(() => {
console.log("App has rendered");
}, []);
Consider an app that renders a number and includes buttons to update the number and toggle visibility:
function App() {
const [num, setNum] = useState(1);
const [show, setShow] = useState(true);
useEffect(() => {
console.log(num);
});
return (
<>
The number is {num}
{show && {num} doubled is {num * 2}
}
>
);
}
Since there is no dependency array, the effect runs after every re-render, even when toggling the visibility.
To prevent unnecessary re-renders, we add num to the dependency array:
useEffect(() => {
console.log(num);
}, [num]);
Now, the effect will only run when num changes.
Variables that depend on other variables must also be included:
function App() {
const [num, setNum] = useState(1);
const message = `The number is ${num}`;
useEffect(() => {
console.log(message);
}, [message]);
}
Since message depends on num, it should be included in the dependency array.
In this reading, you explored:
To continue learning, visit:
Using the dependency array effectively allows you to optimize performance and avoid unnecessary re-renders in your React applications.