Handle callback ref cleanup
Callback refs describe attachment and detachment
Instead of passing a ref object, pass a function to ref on a DOM element. React calls it with the attached node. React 19 supports returning a cleanup function; React calls that function on detachment. With no cleanup return, React 19 currently also supports the older null callback pattern used by React 18. Do not combine assumptions about the two patterns. A callback whose identity changes can be detached and attached again even when its DOM element is reused. These examples use named module functions for stable callback identities or explicitly explain why reattachment can occur.
import { useState } from 'react';function attachSample(node) { if (!node) return; function onFocus() { console.log('Sample field focused'); } node.addEventListener('focus', onFocus); return () => node.removeEventListener('focus', onFocus);}export default function App() { const [show, setShow] = useState(true); return <main><button onClick={() => setShow(v => !v)}>{show ? 'Hide field' : 'Show field'}</button> {show && <label>Sample code <input ref={attachSample} /></label>}</main>;}The callback attaches a native listener to just the sample input. Hide removes the input and its listener; Show attaches a new one. The example uses a native listener to demonstrate lifetime; for ordinary focus handling prefer React onFocus. In development StrictMode, callback refs can get an extra setup and cleanup cycle to expose missing cleanup. Test the final active registrations rather than requiring exact call counts.
Track nodes by a stable data identifier
import { useRef, useState } from 'react';function registerNode(registry, id, node) { registry.set(id, node); return () => { if (registry.get(id) === node) registry.delete(id); };}function SampleRow({ sample, registry }) { return <li><button ref={node => { if (node) return registerNode(registry.current, sample.id, node); }}>{sample.name}</button></li>;}const samples = [{id:'q', name:'Quartz'}, {id:'m', name:'Mica'}];export default function App() { const nodes = useRef(new Map()); const [showMica, setShowMica] = useState(true); const visible = showMica ? samples : samples.slice(0, 1); return <main><h1>Sample registry</h1> <button onClick={() => setShowMica(v => !v)}>Toggle Mica</button> <button onClick={() => nodes.current.get('m')?.focus()} disabled={!showMica}>Focus Mica</button> <ul>{visible.map(sample => <SampleRow key={sample.id} sample={sample} registry={nodes} />)}</ul> </main>;}The map stores actual nodes under the same stable identifiers used for keys. Only event handlers and ref callbacks access its contents; SampleRow receives the ref object, not its mutable current value during render. Inline callbacks here may reattach after rerenders, but cleanup keeps the map correct. The conditional identity check prevents an older cleanup from erasing a newer registration for the same key. Map allocation on each render is harmless for this small example; only the first retained map is used. Hiding Mica removes its entry. Focus Mica is disabled while unavailable. A larger application may use memoized callbacks to avoid unnecessary reattachments; correctness must not depend on memoization.
Recognize the React 18 null callback pattern
import { useRef, useState } from 'react';export default function App() { const input = useRef(null); const [visible, setVisible] = useState(true); function track(node) { input.current = node; } return <main><button onClick={() => setVisible(v => !v)}>Toggle input</button> <button disabled={!visible} onClick={() => input.current?.focus()}>Focus code</button> {visible && <label>Code <input ref={track} /></label>} </main>;}The callback stores either the attached node or null on detachment. It deliberately returns nothing (a block body avoids accidentally returning the assigned node). This pattern is compatible with React 18 and currently React 19; returned cleanup functions require React 19. For this single input, the object ref is simpler. Callback refs are useful when each attachment needs resource-specific work. For a custom component, React 19 can receive ref as a prop, while React 18 generally uses forwardRef; deeper component API design is covered later.
Practice
Register two sample IDs, remove one, replace the remaining node with another node under the same ID, and invoke the older cleanup. Predict map contents. Then use the browser checklist to verify removal, reattachment and StrictMode behavior.