liveBook · Manning

Dependency array

As explained in React Quickly, Second Edition

A dependency array is an array passed to a React effect Hook that specifies values whose changes determine when the effect runs again.

A dependency array is the optional second argument to a React effect Hook. It lists values that control when the effect runs again: when a listed value changes, React runs the previous cleanup, if any, and then runs the effect. section 6.1 section 6.6

Choose the array according to the behavior you need:

  • Skip the array when the effect should run across component renders. section 6.4
  • Use an empty array, [], when the effect should run as the component mounts and should not reload when it updates. section 6.5
  • Include a changing value when the effect should respond only to that value—for example, updating the browser title when title changes. section 6.1
  • Use a flag such as isActive when an effect and its cleanup should rerun whenever that flag changes. section 6.1

Mount-only data loading

useEffect(() => { loadData(url); }, []);\n\nThe empty array makes this effect run when the component mounts, rather than reload data after later component updates. For an unmount-only cleanup, return the cleanup function from the effect: useEffect(() => () => runOnUnmount(), []); section 6.5 section 6.4

Figure 6.1 The useEffect hook here is displayed both as a code snippet and a flowchart. The hook contains an optional effect as well as an optional cleanup function. The effect runs on mount, and the cleanup runs on unmount—if they’re defined, of course. Furthermore, if the effect has a dependency array, the cleanup and effect will also run every time any value reference in the dependency array changes.
06-01

The flowchart connects dependency changes with cleanup and effect execution, showing mount, unmount, and rerun paths. section 6.1

How React Quickly, Second Edition covers it

How deep it goes
Explains skipped, empty, and value-based arrays with lifecycle examples, but defers detailed implementation internals.
Examples
Uses data loading, timers, dialog-close tracking, browser titles, active flags, and unmount cleanup.
What it assumes
Assumes basic functional components and effects while teaching mount, update, unmount, cleanup, and dependency selection through examples.
What you can do after
Apply it via React's useEffect hook to schedule effects and cleanup at selected component lifecycle points.
How it connects
Connects dependency arrays to useEffect, cleanup functions, component lifecycle, and useLayoutEffect.

Also explained in

Compare how 3 books explain dependency array →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.