cleanup function
The function an Effect returns so React can undo what the setup did, such as removing a listener or cancelling a request.
In more detail
React runs it before the Effect runs again with new dependencies and once more when the component unmounts. Every resource opened in setup should be released here; Strict Mode runs an extra setup and cleanup in development to check that.
Examples
The overlay's effect sets body overflow to hidden and makes the app root inert; its cleanup restores the previous overflow and removes inert.return () => window.removeEventListener("keydown", onKey);Related terms
- useEffect — The React hook for running side work, such as adding listeners or changing document.body, after a component renders.
- unmount — When React removes a component and its DOM nodes from the page, discarding its state.
- memory leak — Memory that a program keeps holding although it no longer needs it, so usage grows until the program slows down or crashes.
- AbortController — The standard JavaScript object for cancelling asynchronous work: its signal is handed to the work, and calling abort() cancels it.
Taught in
- Overlay Architecture: Portals, Stacking Contexts & Backdrops — Design Systems & Component Engineering
- Focus Management: Trapping, Restoration & Focus Rings — Design Systems & Component Engineering
- Keys In Depth: Identity Preservation And Identity Resetting — React 19 & Modern Component Architecture
- Diffing Algorithm: Element Type Shifts And Subtree Tear Down — React 19 & Modern Component Architecture
- useEffect Lifecycle: Mount, Dependencies, And Cleanup Phases — React 19 & Modern Component Architecture
- useSyncExternalStore: Tearing-Free Store Subscriptions — React 19 & Modern Component Architecture
- Creating Event Listener Hooks with Clean Teardown Logic — React 19 & Modern Component Architecture