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





