Ref as a Prop
Learn how React 19 allows function components to receive ref as a prop.
We'll cover the following...
In React, we often update the UI declaratively using state and props. But sometimes we need direct access to a DOM element—like focusing an input, measuring its size, or starting an animation. That’s where ref
comes in.
What is ref
?
A ref
(short for “reference”) gives us a direct line to a DOM node or a component instance. It’s like telling React:
“Hey, can I get the actual DOM element so I can do something with it?”
This makes it possible to interact with the DOM directly, without going through React’s state-driven rendering.
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 accept the ref
prop. To make this possible, React provides a utility called forwardRef
...