Search⌘ K

Ref as a Prop

Explore how React 19 allows passing refs as regular props to function components for direct DOM access like focusing inputs. Understand the use of forwardRef and useImperativeHandle for exposing custom methods, and practice building components that use refs for imperative actions.

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 call focus() 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. ...