Return cleanup functions from ref callbacks
Attach a ResizeObserver with a React 19 callback ref, return its disconnect function, and test setup and cleanup when the element unmounts.
Your panel uses a ResizeObserver to report its width. You attach the observer when React hands you the DOM node, but the panel can disappear while its parent stays mounted. Tie cleanup to that ref attachment so the observer follows the element it watches.
Return the observer's cleanup
In React 19, a callback ref can return a cleanup function. Create the observer inside the callback and return a function that disconnects that instance. Put the component below in MeasuredPanel.jsx in a React project.
import { useCallback } from 'react'
export function MeasuredPanel({ children }) {
const attach = useCallback(node => {
if (!node) return
const observer = new ResizeObserver(([entry]) => {
console.log('Panel width:', Math.round(entry.contentRect.width))
})
observer.observe(node)
return () => observer.disconnect()
}, [])
return <section ref={attach}>{children}</section>
}Render <MeasuredPanel>Resize me</MeasuredPanel>, change the width of its container, and you should see Panel width: followed by the size in the console.
One invocation of attach owns one observer. React calls the cleanup when the ref detaches. Returning cleanup tells React to call that function on detach and skip the callback's null invocation. The cleanup closes over the observer for that attachment.
useCallback keeps attach stable during ordinary rerenders. A new function passed as the ref would make React detach the old callback and attach the new one, so an unrelated render could tear down the observer and create a replacement. If the callback reads changing input, include that input in its dependencies so the observer sees the right value.
Exercise detach and reattach
Render the panel behind a toggle. Turn it on, then resize its container. Turn it off and check that the observer disconnects. Add a log inside the cleanup if you need to see it run. Turn the panel back on and repeat the resize, checking that reports resume for the new node.
With Strict Mode at the root, React runs an extra setup and cleanup cycle for callback refs in development. After setup settles, you should have one observer while the panel is present and zero after removal.
If you have several panels on the page, remove one and resize another. Its observer should keep reporting. That check catches code that keeps one shared observer variable and disconnects the most recent observer instead of the one for the node that detached.