Skip to main content

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:

  1. The component first appears on the screen (mounts).
  2. React renders its content.
  3. After the render, React calls useEffect.
  4. 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:

  1. The component mounts → console.log("Subscription set up") runs.
  2. 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 arrayWhen the effect runs
[]Once on mount, cleanup - on unmount
[a, b]On the first render and when a or b changes
no arrayAfter every render

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.