Search⌘ K

Cleanup Functions for Refs

Discover how to use React 19's new ref callback cleanup function to combine setup and teardown logic in one place. This lesson helps you efficiently manage event listeners and DOM interactions, improving component clarity and preventing resource leaks through hands-on examples like outside-click modal closure.

In React, refs are often used to interact directly with DOM elements. While state and props describe the UI declaratively, some cases require imperative access, such as registering event listeners, running animations, or detecting outside clicks. Like other side effects, any listeners or DOM manipulations added via a ref should be cleaned up when the component unmounts.

React 19 introduces a cleaner way to handle this: We can return a cleanup function directly from a ref callback, just like we would from useEffect. This eliminates boilerplate and keeps DOM setup and teardown logic in one place.

Problem with the traditional cleanup

Previously, we used useEffect to attach and clean up things like event listeners or animations. This often splits the setup and teardown logic across different parts of the component, making the code harder to follow.

  • Line 4: Creates a ref (divRef) to access the DOM node.

  • Line 7: Defines the handleClick function to run on click.

  • Lines 8–9: Attaches a click event listener to the ...