...

/

Cleanup Functions for Refs

Cleanup Functions for Refs

Learn how to use cleanup functions within ref callbacks in React 19 to manage DOM resources like event listeners, intervals, or third-party libraries more effectively.

In React, refs are often used to interact directly with DOM elements. While state and props let us describe UI declaratively, there are cases where we need imperative access to elements—like registering event listeners, animations, or handling click detection. But just like with side effects, any resources or listeners attached using a ref should be cleaned up when the component unmounts.

React 19 introduces a cleaner way to handle this: we can now 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 traditional cleanup

Previously, we had to use useEffect to both attach and clean up things like event listeners or animations. This often separated the logic for setting up and tearing down a ref-based interaction.

  • 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 ...