- Home
- /
- Tutorials
- /
- React Tutorial
- /
- Effect Dependencies
Effects and Refs
Effect Dependencies
The dependency array is not a schedule. It is a list of values the effect reads, and React re-runs the effect whenever one of them differs from last time.
The three forms
- No array - runs after every render.
- Empty array - runs once, after the first render.
- Array with values - runs again whenever one of them changes.
All three, counted
jsx
function Deps() {
const [a, setA] = React.useState(0)
const [b, setB] = React.useState(0)
const counts = React.useRef({ every: 0, once: 0, onA: 0 })
React.useEffect(() => { counts.current.every++ })
React.useEffect(() => { counts.current.once++ }, [])
React.useEffect(() => { counts.current.onA++ }, [a])
return (
<div>
<p>a = {a}, b = {b}</p>
<button onClick={() => setA(a + 1)}>Change a</button>{" "}
<button onClick={() => setB(b + 1)}>Change b</button>
<pre style={{ background: "#f1f5f9", padding: 8 }}>
{`no array : ${counts.current.every}
empty [] : ${counts.current.once}
[a] : ${counts.current.onA}`}
</pre>
<p style={{ color: "#64748b" }}>Press "Change b" a few times and watch which counters move.</p>
</div>
)
}
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<Deps />)