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

Also available as: JSON · Markdown
89%Fix Rate
91%Confidence
100Evidence
2022-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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

  2. 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

  3. 85% success Use flushSync before accessing ref after a state update
    import { flushSync } from 'react-dom'; flushSync(() => { setState(newValue); }); ref.current.focus();

    Sources: https://react.dev/reference/react-dom/flushSync

Dead Ends

Common approaches that don't work:

  1. 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.

  2. 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

Leads to:
Preceded by:
Frequently confused with: