Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React 19 Ref Cleanup Functions and forwardRef Deprecation

ref is a normal prop now and a ref callback may return a cleanup function, which breaks every implicit-return callback. Migration steps and the leak it fixes.

~5 min readReact
#React#Refs#Migration#TypeScript
3D illustration of a React atom cube with a ref plug becoming a plain socket and a cleanup thread unspooling from it

Introduction & Quick Summary

Symptom. After upgrading to React 19, forwardRef still works but every declaration is deprecated and the editor strikethroughs it; a ref callback that used an arrow function's implicit return starts failing type-check with Type '(instance: HTMLDivElement | null) => HTMLDivElement | null' is not assignable to type 'Ref<HTMLDivElement>'; and a component that attaches an observer, listener, or third-party widget in a ref callback leaks it, because nothing ever cleaned up.

Cause. React 19 makes ref an ordinary prop on function components, so forwardRef is a compatibility wrapper rather than a requirement. It also allows a ref callback to return a cleanup function, which forces the callback's type to void | (() => void) — an implicit return of el, or of an assignment expression's value, is now a type error and a runtime warning, because a non-void return is read as a cleanup function. The cleanup half is new behaviour: before 19 the only signal was a second call with null, which arrives on every re-render, not only on detach.

Fix. Delete forwardRef, take ref from props with the Ref<T> type and pass it through, write ref callbacks as block bodies that return an explicit cleanup function, and replace any el => (ref.current = el) with a block body so nothing is returned by accident.

Core Mechanics, Signatures & Reproducible Setup

The ref contract changed shape in one release. Compare a React 18 component with its React 19 equivalent:

tsx
// React 18 — the wrapper exists and its type is ForwardRefExoticComponent const Search = forwardRef<HTMLInputElement, Props>(({ onFocus }, ref) => ( <input ref={ref} onFocus={onFocus} /> )); Search.displayName = "Search";
tsx
// React 19 — ref is a prop like any other type Props = { onFocus?: () => void; ref?: Ref<HTMLInputElement> }; function Search({ onFocus, ref }: Props) { return <input ref={ref} onFocus={onFocus} />; }

The ref callback signature widened to accept a returned cleanup:

ts
type RefCallback<T> = (instance: T | null) => void | (() => void);

That single change is the source of almost every React 19 migration error. TypeScript now checks the arrow body's expression type against void | (() => void), so anything returning a value is rejected, while a block body that returns nothing still satisfies it.

Reproduce the leak with three lines: mount a component whose ref callback calls new ResizeObserver(...).observe(el), unmount it, and observe the callback firing after detach. In React 19 the fix is local to the callback:

tsx
const boxRef = useCallback((el: HTMLDivElement | null) => { if (!el) return; const observer = new ResizeObserver(() => setWidth(el.clientWidth)); observer.observe(el); return () => observer.disconnect(); // runs before the next ref or unmount }, []);

The callback is created once (useCallback) and the cleanup runs when the element is replaced or removed. Without useCallback, the callback identity changes every render, React detaches and reattaches, and the observer is recreated on every render — correct output, wasted work.

Key Comparison Table

ConcernReact 18React 19
ref on a function componentrequires forwardRefa normal prop
forwardRefrequireddeprecated, still works
Ref callback return valueignored, must be voidvoid | (() => void), cleanup
Cleanup signalsecond call with nullexplicit returned function
element.refreadableremoved; read props
useRef() with no argumentallowedneeds an initial value
Implicit-return ref callbacktoleratedtype error and runtime warning
Migration patternWorks in 19Do instead
ref={el => (this.el = el)}noblock body, no return
forwardRef((p, ref) => …)yes, deprecatedfunction C({ ref, …p })
ref inside props spreadstripped in 18passes through in 19
ref to a class componentinstanceinstance, unchanged
Cleanup via useEffect(() => …)worksstill works; ref cleanup is shorter

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

1. The implicit-return type error

ref={el => (this.node = el)} returns the assigned element. React 18 ignored it; React 19 treats it as a cleanup function and calls it on detach, which throws TypeError: ... is not a function.

tsx
// broken <div ref={(el) => (nodeRef.current = el)} /> // fixed <div ref={(el) => { nodeRef.current = el; }} />

The runtime warning in development is Unexpected return value from a callback ref. Treat it as an error, not noise: it means React is holding a value it will try to call. @typescript-eslint/no-confusing-void-expression catches the same pattern before it ships.

2. Migrating forwardRef without breaking the public type

Callers use <Search ref={r} />, and that keeps working when the component takes ref as a prop, because JSX passes ref as a prop in React 19. Two details differ: the exported type is a plain function, and displayName no longer affects devtools naming in the same way because the function has a name already.

tsx
// before: ForwardRefExoticComponent<Props & RefAttributes<HTMLInputElement>> export const Search = forwardRef<HTMLInputElement, Props>(function Search(props, ref) { … }); // after: (props: Props) => JSX.Element, ref inside Props export function Search({ ref, ...props }: Props) { … }

If a wrapper library re-exports the type, React.ElementRef<typeof Search> stops resolving to HTMLInputElement. Use ComponentRef<typeof Search>, which reads the prop type instead of the exotic ref attribute.

3. A ref callback that must also run cleanup on dependencies

A ref callback cannot depend on state directly — its identity is the only dependency React sees. Move the logic into useEffect when the cleanup needs to react to props:

tsx
const ref = useRef<HTMLDivElement>(null); useEffect(() => { const el = ref.current; if (!el) return; const ro = new ResizeObserver(() => setWidth(el.clientWidth)); ro.observe(el); return () => ro.disconnect(); }, [slot]); // re-attaches when slot changes, same as a new ref callback

Ref cleanup is the shorter form when the setup depends only on the element. useEffect remains the right tool when it depends on other values.

4. useRef now requires an argument

useRef<HTMLDivElement>() compiles to MutableRefObject<HTMLDivElement | undefined> and is rejected in React 19 types. Pass null and type it as the element or null:

ts
const ref = useRef<HTMLDivElement>(null); // RefObject<HTMLDivElement | null>

The same change affects createRef, whose result is now RefObject<T | null> rather than RefObject<T>.

5. Class components and element.ref

A class component receiving ref still gets its instance, but reading props.ref inside it returns the forwarded ref instead of being stripped, and element.ref is gone. Code that probed the DOM node from a parent breaks.

tsx
// before const isForwarded = el.ref != null; // after — read the prop you actually set const isForwarded = "ref" in el.props;

6. Third-party widget cleanup ordering

React calls the old callback's cleanup before the new callback runs, and cleanup on unmount before the DOM node is removed. A widget that must destroy before its container leaves the document is therefore safe with ref cleanup and was racy with the null call, because multiple null calls could arrive for one attach.

tsx
const mount = useCallback((el: HTMLDivElement | null) => { if (!el) return; const chart = createChart(el, { data }); return () => chart.destroy(); // guaranteed once per attach }, [data]);

Common Compilation/Runtime Mistakes & Version Gotchas

  • forwardRef kept "for safety". It works in 19 but is deprecated, and a future major removes it; migrate with the React 19 codemod.
  • Arrow-body ref callbacks. Any implicit return becomes a cleanup function. Always use a block body.
  • Cleanup returning a promise. An async ref callback returns a Promise, which React does not await and cannot call — the type error is the warning.
  • useRef<T>() with no argument. Rejected by React 19 types; pass null.
  • React.ElementRef in library code. Use ComponentRef, which resolves the ref prop.
  • Assuming cleanup runs on every render. It runs only when the callback identity changes or the element detaches; wrap in useCallback to control that.
  • @types/react left on 18 while react is 19. The two disagree about RefCallback, and every ref produces a type error that is not real.

Related tools. Inspect component props and ref objects in a captured React DevTools dump with the JSON formatter, diff the upgraded .d.ts of a wrapper library against the previous release with the text diff, and check whether two ref callbacks in a stack trace come from the same build by hashing the bundles with the hash generator.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.