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.
// 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);true function focused hello
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.