CodeBlanks Logo Icon CodeBlanks

Dependency array

Learn the useEffect dependency array.

What is the dependency array?

The second argument of useEffect is the dependency array. It decides when the effect re-runs. When you write useEffect(effect, [a, b]), the effect runs only when a or b changes.

There are three cases: with no array it runs on every render; an empty array [] runs only on mount; a value list [a, b] runs when one of those values changes. A wrong dependency array leads to extra runs or to stale-value bugs, so write the array carefully.

Three behaviours

You should know three behaviours of the dependency array. No array runs the effect after every render. An empty array [] runs the effect once, on mount; this is the most common pattern.

A filled array [a, b] runs on mount and when a or b changes. The array takes primitive values (number, string, boolean); objects and arrays get a new reference on every render, so be careful. The exhaustive-deps lint rule helps you write dependencies correctly.

Practice Mount effect with an empty array

Write a Logger component. Use useEffect to log "Started" with console.log. Leave the dependency array empty ([]) so it runs only on mount. The component returns <Text>Log</Text>.

Starter code

App.js
// Import useEffect

function Logger() {
  // Log "Started" with useEffect; array empty

  return <Text>Log</Text>;
}

Sample solution

App.js
import { useEffect } from "react";
import { Text } from "react-native";

function Logger() {
  useEffect(() => {
    console.log("Started");
  }, []);
  return <Text>Log</Text>;
}

Questions and answers

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

1 Complete the empty array

Question
useEffect(() => {
  console.log("Mount");
}, ____);
Answer
useEffect(() => {
  console.log("Mount");
}, []);

Explanation: The empty array runs only on mount.

2 When does this effect run?

App.js
useEffect(() => {
  saveProfile(profile);
}, [profile]);
  • Only on mount
  • When profile changes Correct answer
  • Never
  • Her render'da

Explanation: The filled array re-runs when profile changes.

3 Match the behaviour to the scenario

Term Meaning
No array Every render
[] Only on mount
[a, b] When a or b changes
useEffect Side effect hook

All lessons in Intermediate