Callback refs: with and without a cleanup
Inline callbacks are new functions every render, so a re-render detaches and re-attaches both. All detaching happens before any attaching. When the boxes are removed, A is called with null and B's cleanup runs.
Since React 19 a function component receives ref as an ordinary prop and can pass it on to a DOM element; older code wraps the component in forwardRef instead, and ref callbacks can now return a cleanup function.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a Button component that accepts every normal button prop plus ref (React 19 style), and a parent that focuses it on mount.
Convert this to React 19 style: const Search = forwardRef((props, ref) => <input ref={ref} type="search" {...props} />);
Explain it without notes
How do you let a parent get a ref to a DOM element inside your component in React 19? How was it done before?
What changed about callback refs in React 19?
Why does an inline callback ref run on every render, and when does that matter?
Why are a component's DOM nodes private by default?
Preview
Console
Nothing logged yet.Expected console output
A got <p.a>
B attached <p.b>
--- re-render ---
A got null
B cleanup
A got <p.a>
B attached <p.b>
--- hide ---
A got null
B cleanup