The Ref Callback Pattern
You'll learn how to pass a function to the ref prop for more control over when and how refs are set.
The Core Idea
So far, you've passed ref objects (created with useRef) directly to elements. But React also accepts a function as the ref prop. This function gets called automatically with the DOM node when the element mounts, and with null when it unmounts.
Think of it like a notification system: instead of checking a mailbox (ref.current) whenever you want, React calls your phone (your callback function) the moment mail arrives.
How It Works
function MyComponent() {
const handleRef = (node) => {
if (node) {
console.log('Element mounted:', node);
node.focus();
} else {
console.log('Element unmounted');
}
};
return <input ref={handleRef} />;
}
React calls handleRef(node) when the input mounts and handleRef(null) when it unmounts.
Why Use This Pattern?
Advanced initialization: You might need to perform setup logic immediately when the element appears, without waiting for an effect.
Cleanup logic: The callback receives null on unmount, letting you clean up references or observers right away.
Dynamic logic: You can perform different actions based on the node's properties or run side effects that depend on the element existing.
Comparing to ref Objects
With useRef, you store and check later. With ref callbacks, React tells you immediately when things change.
Key Takeaway: The ref callback pattern gives you a function that React calls with the DOM node on mount and null on unmount, enabling advanced initialization and cleanup logic right when the element lifecycle changes.