Hint
Ref callbacks are an alternative to useRef + useEffect for DOM setup. They fire synchronously during commit phase and automatically clean up. Useful for measuring DOM on mount.
const log = [];
// Ref callback: called with element on mount, null on unmount
function useRefCallback(callback) {
return function refFn(element) {
if (element !== null) {
callback(element); // mounted
} else {
callback(null); // unmounted
}
};
}
// Simulate component lifecycle
function simulateMount(refFn) {
const element = { tag: 'div', id: 'app' };
refFn(element); // mount
return element;
}
function simulateUnmount(refFn) {
refFn(null); // unmount
}
const refFn = useRefCallback(el => {
if (el) log.push('mounted: ' + el.tag);
else log.push('unmounted');
});
const el = simulateMount(refFn);
console.log(log.length);
simulateUnmount(refFn);
console.log(log.join(' | '));1 mounted: div | unmounted
Explanation: Ref callback fires with the DOM element on mount, then null on unmount. This gives you exact mount/unmount timing without useEffect.
Key Insight: Ref callbacks are an alternative to useRef + useEffect for DOM setup. They fire synchronously during commit phase and automatically clean up. Useful for measuring DOM on mount.