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:
- The component renders for the first time ->
useEffectruns. - The user clicks the button -> the
countstate updates -> the component re-renders. useEffectruns again.- 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 arrayNow the effect fires once after the first render - the equivalent of componentDidMount().
Summary
| Dependency array | When the effect runs |
|---|---|
| missing | After every render |
[] | Only once - on mount |
[a, b, c] | On the first render and whenever any dependency changes |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.