the callback ref pattern provides us with a more powerful way to have control for cases when a child is being added or removed dynamically, that means the child does not have the same lifetime as the parent or you need to perform any effect when a ref has been mounted.
Let’s consider a simple example where part of a form only appears when the user clicks on the first button and when it happens we want the newly shown input to be focused. Since the second input is added dynamically, when the state changes and the visible variable is set to true, the best approach for this is using the callback ref.
The useRef doesn’t notify you when its content changes. Mutating the .current property doesn’t cause a re-render. Therefore, to run any effect when React attaches or detaches a ref to a DOM node, we would need to use the callback ref.
With callback ref, when the second input shows up and the ref is attached to the <input>, the callbackRef function is called with the HTMLInputElement. Then if the node is not null/undefined we call the focus() method to achieve what we wanted.
You need to focus an input element when a modal opens. How would you set up the ref using a callback ref, and why might you choose that over useRef?
If you have a list of items where each item needs its own ref for measuring height, how would you implement the refs with a callback function?
We have a component that receives a ref from its parent and also needs to attach a DOM node for an animation library. Explain how you'd combine a forwarded ref with a callback ref, and what pitfalls to watch out for.
During a code review you notice a component using a callback ref that sometimes receives null unexpectedly, causing a crash. Walk me through how you'd debug the issue and decide if the callback ref is appropriate.
In a large application, you need to replace legacy string refs with a pattern that supports dynamic ref assignment and cleanup. Describe the design you’d propose using callback refs, and discuss performance and memory considerations.
When integrating a third‑party UI library that expects a DOM node at mount time, why might you prefer a callback ref over useRef, and how would you ensure the ref is stable across re‑renders in a high‑traffic component?
Our team is planning a migration to React 18 with concurrent features, and we have many components using callback refs for measuring layout. What architectural guidelines would you set to decide when to keep callback refs versus switching to useRef or other patterns, considering future concurrency and team maintainability?
Imagine a cross‑team library that provides a higher‑order component exposing an imperative API via refs. How would you design its API to allow both callback refs and ref objects, and what trade‑offs does that introduce for long‑term code health?