react
ref_error
ai_generated
true
TypeError: Cannot read properties of null (reading 'focus'). Ref callback receives null on unmount.
ID: react/react-ref-callback-error
89%Fix Rate
91%Confidence
100Evidence
2022-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 18 | active | — | — | — |
Root Cause
Ref callback function or ref.current accessed when the DOM node is null. Callback refs are called with null on unmount. useRef.current is null before the component mounts or after it unmounts.
genericWorkarounds
-
90% success Add a null check before accessing ref.current methods
if (ref.current) { ref.current.focus(); } or ref.current?.focus();Sources: https://react.dev/learn/manipulating-the-dom-with-refs
-
92% success Use a callback ref that checks for null
const callbackRef = useCallback((node) => { if (node !== null) { node.focus(); } }, []); <input ref={callbackRef} />Sources: https://react.dev/reference/react-dom/components/common#ref-callback
-
85% success Use flushSync before accessing ref after a state update
import { flushSync } from 'react-dom'; flushSync(() => { setState(newValue); }); ref.current.focus();
Dead Ends
Common approaches that don't work:
-
Access ref.current immediately after calling setState
75% fail
State updates are asynchronous; the DOM has not yet updated when you access the ref. The ref still points to the old DOM or is null.
-
Use a setTimeout to delay ref access
65% fail
Timing-based workaround that is fragile and race-condition prone. May work in dev but break in production under load.
Error Chain
Preceded by:
Frequently confused with: