Course contentsShow
← React
Lesson 1515 of 2,39637. React 19 and BeyondFree lesson

Cleanup Functions in Refs

Ref callbacks can now return cleanup functions, simplifying resource disposal when elements unmount.

Cleanup Functions in Refs

You'll learn how ref callbacks can now return cleanup functions to automatically dispose of resources when elements unmount.

The Problem Refs Used to Have

Before React 19, if you set up a resource in a ref callback (like an observer, event listener, or external library instance), you had to manually clean it up using useEffect. This meant writing two separate pieces of code for what was really one logical operation: "attach this thing when the element mounts, detach it when it unmounts."

The Cleanup Pattern

Now, ref callbacks can return a cleanup function, just like useEffect does. When the element unmounts or the ref changes to a different element, React automatically calls your cleanup function.

<div ref={(node) => {
  if (node) {
    // Setup: attach something to the DOM node
    const observer = new IntersectionObserver(/* ... */);
    observer.observe(node);
    
    // Return cleanup function
    return () => {
      observer.disconnect();
    };
  }
}} />

Why This Matters

Think of it like a hotel checkout system. Previously, you'd check in at the front desk (ref callback) but had to remember to stop by a separate desk (useEffect cleanup) to check out. Now, you hand the front desk a checkout instruction card when you check in, and they handle it automatically when you leave.

This pattern is especially useful for third-party libraries, resize observers, intersection observers, or any DOM-based resource that needs disposal.

Key Takeaway: Ref callbacks can now return cleanup functions, letting you handle setup and teardown in one place instead of splitting logic between refs and effects.