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 effectively.
We'll cover the following...
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 ...