Empty dependency array
When an effect with an empty dependency array runs
If you pass an empty dependency array ([]) to useEffect,
the effect runs only once -
after the first render (that is, when the component mounts).
Example
javascript
import { useEffect } from "react";
function Example() {
useEffect(() => {
console.log("Effect ran once on mount");
}, []); // empty dependency array
return <div>Example</div>;
}What happens:
- The component first appears on the screen (mounts).
- React renders its content.
- After the render, React calls
useEffect. - The effect will never run again, even if the component re-renders.
Analogy with classes
Such useEffect(() => {...}, []) is fully analogous to the method:
javascript
componentDidMount() {
// called once on mount
}in a class component.
Cleanup on unmount
If the effect returns a function - it will be called only when the component unmounts (is removed from the screen).
javascript
useEffect(() => {
console.log("Subscription set up");
return () => {
console.log("Subscription removed");
};
}, []);Order:
- The component mounts →
console.log("Subscription set up")runs. - The component is removed →
console.log("Subscription removed")runs.
Typical use cases for []
- Make an API request when the page loads
- Attach an event listener (and unsubscribe on removal)
- Set the page title (
document.title) - Start a timer or animation once
Summary
| Dependency array | When the effect runs |
|---|---|
[] | Once on mount, cleanup - on unmount |
[a, b] | On the first render and when a or b changes |
| no array | After every render |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.