Ref as a Prop
Explore how React 19 improves handling refs by allowing you to pass refs as regular props to function components without the need for forwardRef. Understand how to directly access DOM nodes, simplify component communication, and expose custom methods using forwardRef and useImperativeHandle. Apply these concepts through practical exercises like toggling password visibility and resetting inputs.
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
useEffectto callfocus()on the input when the component mounts.Line 10: Attaches the
refto 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 ...