Under The Hood
frontend react React 19

Ref as Plain Prop & useRef Cleanup Lifecycle Functions

Last updated
Prerequisites:
useRef basics
DOM element references
  • react
  • ref
  • forwardRef
  • cleanup
  • dom
  • react-19

Read at your depth

The practical view

In React 19, `forwardRef` is deprecated. You can pass `ref` as a standard prop directly into functional components: `function MyInput({ ref, ...props })`. Additionally, callback refs now support **cleanup functions**: `ref={(node) => { attach(node); return () => detach(node); }}`. The returned cleanup function executes whenever the node is removed from the DOM, eliminating manual `null` checks.

The same idea in other frameworks

react equivalent
`ref={(el) => { observer.observe(el); return () => observer.disconnect(); }}`

Legacy vs modern

forwardRef + Null Checking vs Direct Ref Prop + Cleanup Function

`forwardRef` is boilerplate-heavy and `null` checking is error-prone; React 19 enables plain ref props and automatic teardown returns.

before → after
forwardRef & Null Check (React 18)
const Input = forwardRef((props, ref) => <input ref={ref} />); // ❌ Deprecated forwardRef
React 19 Plain Ref + Cleanup Return
function Input({ ref, ...props }) { return <input ref={ref} />; } // ✅ NEW

Interview gotchas

Context

Interviewers test your attention to subtle arrow function return bugs in React 19.

The mechanical answer

If a callback ref returns a non-function value (e.g. an implicit arrow function return like `ref={el => map.set(id, el)}` which returns `Map`), React 19 will throw a runtime error warning that ref callbacks must either return a cleanup function or `undefined`.

Trap

Avoid writing concise arrow functions with single-expression returns if they return a value. Wrap them in braces: `ref={el => { map.set(id, el); }}`.

Under The Hood — a multi-depth technical interview hub.

Third-party licenses Press ⌘ K to search.