Advertisement
Advanced React, Refs, useRef & forwardRef

What is forwardRef and why is it needed when passing a ref to a custom component?

Short answer

By default, a ref you attach to a custom component does not automatically reach the actual DOM element inside it, since refs only work directly on native HTML elements like input or div.

Save React mock interview
Advertisement
AModel answer
By default, a ref you attach to a custom component does not automatically reach the actual DOM element inside it, since refs only work directly on native HTML elements like input or div. forwardRef lets a custom component accept a ref as a second argument and manually pass it down to the specific inner element you want the parent to actually control.
const CustomInput = React.forwardRef(function CustomInput(props, ref) {
  return <input ref={ref} {...props} />;
});

function Form() {
  const inputRef = useRef(null);
  return (
    <>
      <CustomInput ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </>
  );
}
Real-world example
A shared design system component wraps a plain input with extra styling, and uses forwardRef so any page using it can still directly focus the actual input element from outside, exactly as if it were a native input.
Likely follow-ups
  • What happens if you try to pass a ref to a custom component that does not use forwardRef?
  • How does forwardRef work together with the useImperativeHandle hook?
Related topics