liveBook · Manning

Resource cleanup

As explained in React in Depth

A cleanup function is a function returned by a React effect to undo or release resources created by that effect.

A cleanup function is returned by a React effect to undo or release resources created by that effect. Effects may return nothing or a function, but no other value is valid. section 6.1.4

Cleanup runs before an effect with changed dependencies runs again, and it may run during development when Strict Mode repeats effects. Treat it as part of the effect’s lifecycle rather than as an optional callback. section 3.1.2

Use these implementation rules:

  • Return nothing when the effect creates no resource or when a guard prevents setup. section 6.1.4
  • Keep effects and cleanup behavior predictable when Strict Mode invokes lifecycle work repeatedly during development. section 3.1.2

Cleaning up a timer

When a timer is running, create the interval and return a cleanup function that clears it. When it is not running, use a bare return instead of returning false.

How React in Depth covers it

How deep it goes
Defines the return contract, demonstrates interval teardown, and traces cleanup ordering; it does not generalize beyond focused effect examples.
Examples
Uses a running timer, clearInterval, invalid boolean returns, and console logs from repeated Strict Mode effects.
What it assumes
Assumes React effect fundamentals and TypeScript familiarity while clarifying the cleanup return contract from the effect API.
What you can do after
Diagnose TypeScript effect-return errors and implement interval cleanup with a valid React effect return.
How it connects
Connects cleanup functions with useEffect, useLayoutEffect, TypeScript, intervals, and React Strict Mode.

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 React in Depth. The section links point to the parts of the book it draws on.