Skip to main content

When does an effect without dependencies run?

When does an effect without dependencies run

If you do not pass a dependency array at all, the effect will run after every render of the component.


Example:

javascript
import { useState, useEffect } from "react"; function Example() { const [count, setCount] = useState(0); useEffect(() => { console.log("Effect ran"); }); // <- no dependency array! return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ); }

What happens:

  1. The component renders for the first time -> useEffect runs.
  2. The user clicks the button -> the count state updates -> the component re-renders.
  3. useEffect runs again.
  4. And so on - every render = a new effect call.

This can be a problem

An effect like this:

  • runs too often,
  • can cause infinite loops (if state is changed inside useEffect).

Example of an infinite loop

javascript
useEffect(() => { setCount(count + 1); // changes state });

Every render calls setCount, which triggers a new render, and the effect runs again -> an infinite render loop.


How to prevent it

To run the effect only once, on mount, pass an empty dependency array:

javascript
useEffect(() => { console.log("Effect ran once"); }, []); // <- empty array

Now the effect fires once after the first render - the equivalent of componentDidMount().


Summary

Dependency arrayWhen the effect runs
missingAfter every render
[]Only once - on mount
[a, b, c]On the first render and whenever any dependency changes

Short Answer

Interview ready
Premium

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