MediumRefs & Side Effects💻 Output Question

forwardRef — parent accesses child's DOM node

💡

Hint

forwardRef is the mechanism for parent components to call DOM methods on a child's internal elements. Pair with useImperativeHandle to expose a controlled API instead of raw DOM.

What does this output?

// Simulates forwardRef pattern
function FancyInput(props, ref) {
  const input = {
    focus() { console.log('focused'); },
    value: props.defaultValue || '',
  };
  if (ref) ref.current = input;
  return input;
}

function withForwardRef(Component) {
  return (props) => {
    const ref = props._ref; // simulated forwardRef
    return Component(props, ref);
  };
}

const ForwardedInput = withForwardRef(FancyInput);

// Parent creates ref and passes it
const inputRef = { current: null };
ForwardedInput({ defaultValue: 'hello', _ref: inputRef });

console.log(inputRef.current !== null);
console.log(typeof inputRef.current.focus);
inputRef.current.focus();
console.log(inputRef.current.value);

Correct Output

true
function
focused
hello

Why this output?

Explanation: forwardRef passes the ref from parent to the internal DOM node. Parent can then call imperative methods like focus().

Key Insight: forwardRef is the mechanism for parent components to call DOM methods on a child's internal elements. Pair with useImperativeHandle to expose a controlled API instead of raw DOM.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz