HardRefs & Side Effects💻 Output Question

Ref callback — fires on mount and unmount

💡

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.

What does this output?

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(' | '));

Correct Output

1
mounted: div | unmounted

Why this output?

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.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz