liveBook · Manning

Resource cleanup

As explained in D3.js in Action, Third Edition

A cleanup function is a function returned from a React effect to release resources or prevent work after the effect is no longer active.

A cleanup function is the function returned from a React useEffect hook. It runs when the component unmounts, allowing asynchronous work to stop updating state after the component is no longer active. section 8.3

For a data-fetching effect:

  • Set a mounted flag to true when the effect begins. section 8.3
  • Check the flag before calling state setters inside the Promise callback. section 8.3
  • Return a cleanup function that sets the flag to false when the component unmounts. section 8.3

Guarding a D3 request

useEffect(() => { let mounted = true; d3.json(dataURL).then(data => { if (mounted) { setData(data); setLoading(false); } }); return () => mounted = false; }, []);

useEffect(() => {
  ...
  let mounted = true
  d3.json(dataURL).then(data => {
    if (mounted) {
      setData(data);
      setLoading(false);
    }
  });
  return () => mounted = false;
}, []);

Inspect the compact implementation of the mounted flag, guarded Promise callback, and returned cleanup function. section 8.3

How D3.js in Action, Third Edition covers it

How deep it goes
Demonstrates a mounted-flag pattern but does not compare alternative cleanup strategies.
Examples
Uses a D3 JSON request that updates loading and data state through a guarded Promise callback.
What it assumes
Assumes familiarity with React state, useEffect, component mounting, and JavaScript Promise callbacks.
What you can do after
Apply it via React useEffect to prevent updates from an unfinished D3 request after unmounting.
How it connects
Connects React effects, component unmounting, Promises, state updates, and D3 data fetching.

Also explained in

Compare how 6 books explain resource cleanup →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.