CodeBlanks Logo Icon CodeBlanks

Dependency array

Learn that the dependency array controls when the effect runs.

Dependency array

The second argument to useEffect is a dependency array: useEffect(fn, [count]). The effect runs only when the values in this array change.

An empty array [] runs the effect only on the first render. No array runs it on every render. This control prevents needless runs.

You must list every outside value the effect uses as a dependency; otherwise it goes stale.

Three run modes

useEffect has three modes: no array (every render), empty array (first render), filled array (on change). Which one you pick depends on the effect's purpose.

Forgetting dependencies is a common bug; outside values must always be listed. The eslint-plugin-react-hooks warns about missing dependencies.

The right dependency array makes the effect run at the right time.

Practice Effect with dependencies

Complete the skeleton. Write a Counter component; import useState and useEffect. Define const [count, setCount] = useState(0);. Call useEffect(() => { document.title = String(count); }, [count]);. Return <button onClick={() => setCount(count + 1)}>{count}</button>. Export it.

Starter code

App.jsx
import { useState, useEffect } from "react";

// Define Counter here

Sample solution

App.jsx
import { useState, useEffect } from "react";

function Counter() {
  const [count, setCount] = useState(0);
  useEffect(() => { document.title = String(count); }, [count]);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

export default Counter;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When does useEffect(fn, []) run?

App.jsx
An empty array means "no dependencies".
  • Every render
  • Only on unmount
  • Never
  • Only on the first render Correct answer

Explanation: An empty array runs the effect once on the first render.

2 Dependency array: fill in the missing part

Question
useEffect(() => { fetch(url); }, [____])
Answer
useEffect(() => { fetch(url); }, [url])

Explanation: The effect re-runs when url changes.

3 Dependency array: match the terms

Term Meaning
[] First render
[count] On count change
no array Every render
[url, page] Multiple deps

All lessons in Beginner