Ref as a Prop
Learn how React 19 allows function components to receive ref as a prop.
In React, most of our interactions with UI are handled declaratively using state and props. However, there are times when we need to imperatively access a DOM element—like focusing an input, measuring its size, or triggering animations. This is where ref
comes into play.
What is ref
?
A ref (short for “reference”) gives us a direct line to a DOM node or a component instance. Think of it like asking React:
“Hey, can I get the actual DOM element so I can do something with it?”
This allows us to interact with the DOM in a more hands-on way, without relying solely on React state.
Line 4: Creates a new ref using
useRef()
.Lines 6–8: Uses
useEffect
to callfocus()
on the input when the component mounts.Line 10: Attaches the
ref
to the<input>
element, giving us direct access to it.
What Are forwardRef
and useImperativeHandle
?
When we want to pass a ref from a parent component into a child component, function components by default don’t ...