Today I learned about ref callbacks
It escaped my attention, we can pass a callback function as a ref for an element in React,
not just an object (like from useRef).
const scroller = (node: HTMLDivElement) => { if (!node) return; node.scrollIntoView({ behavior: "smooth" });};
// somewhere in component <div ref={scroller} />How it works:
- when the element is added to the DOM, React calls the
refcallback with the DOM node as its argument - when the element is removed from the DOM, React calls the
refcallback withnull - also the callback is invoked whenever a new callback is assigned (on each render if it is written as a simple function)