More React answers

by Danny
Published 3 min read

A ref only points at a DOM node after React has committed it to the page. Learn when ref.current is null, how to read it at the right time, and how callback refs help.

The short answer

#

React fills in ref.current after it has put the element on the page, and sets it back to null when the element is removed. If you read it during render, before mount, or while the element is not rendered, you get null. Read it in an effect or an event handler, and make sure the ref actually reaches a DOM element.


_11
function SearchBox() {
_11
const inputRef = useRef<HTMLInputElement>(null);
_11
_11
// inputRef.current is null here, during render
_11
_11
useEffect(() => {
_11
inputRef.current?.focus(); // set by now
_11
}, []);
_11
_11
return <input ref={inputRef} />;
_11
}

Why it happens

#

Rendering a component only describes what the screen should look like. The real DOM nodes are created or updated afterwards, in the commit phase. React attaches refs during commit, then runs your effects. So the order inside one render is: your component function runs, React updates the DOM and sets refs, then effects run.

That means ref.current is null whenever the element does not exist yet or no longer exists. The common cases are:

  • Reading the ref in the component body, during the first render.
  • The element is behind a condition, such as isOpen && <dialog ref={ref} />, and is not rendered right now.
  • The ref is passed to your own component, which does not pass it on to a DOM element.
  • The element mounts later than the effect that reads the ref, for example inside a lazy component or after data loads.

How to fix it

#

Read refs in effects and event handlers

Effects and event handlers run after commit, so the ref is set if the element is on the page. Use optional chaining so the code is safe when it is not.


_14
function Chat({ messages }: { messages: Message[] }) {
_14
const endRef = useRef<HTMLDivElement>(null);
_14
_14
useEffect(() => {
_14
endRef.current?.scrollIntoView({ behavior: 'smooth' });
_14
}, [messages.length]);
_14
_14
return (
_14
<div>
_14
{messages.map((m) => <p key={m.id}>{m.text}</p>)}
_14
<div ref={endRef} />
_14
</div>
_14
);
_14
}

If you need to measure the element before the browser paints, to avoid a flicker, use useLayoutEffect instead.

Use a callback ref for elements that come and go

An effect with an empty dependency list runs once. If the element appears later, the effect has already run and missed it. A callback ref runs every time the element is attached, so it always sees the node. In React 19 a callback ref can return a cleanup function, which React calls when the element is removed.


_11
function Panel({ isOpen }: { isOpen: boolean }) {
_11
return isOpen ? (
_11
<div
_11
ref={(node) => {
_11
const observer = new ResizeObserver(() => console.log('resized'));
_11
observer.observe(node);
_11
return () => observer.disconnect();
_11
}}
_11
/>
_11
) : null;
_11
}

If the callback is defined inline, React will detach and reattach it on every render. Wrap it in useCallback when the setup work is expensive.

Pass the ref through your own components

A ref on a component you wrote does nothing until that component puts it on a DOM element. In React 19, ref is an ordinary prop for function components, so you no longer need forwardRef.


_10
function TextField({ ref, ...props }: React.ComponentProps<'input'>) {
_10
return <input ref={ref} className="field" {...props} />;
_10
}
_10
_10
// Parent
_10
const ref = useRef<HTMLInputElement>(null);
_10
<TextField ref={ref} />;

In React 18 and earlier, the child needs forwardRef instead.

Check the element is really rendered

If the ref is still null in an effect, the element was not on the page at that moment. Add the condition that controls it to the effect's dependencies, so the effect runs again when the element appears.


_10
useEffect(() => {
_10
if (isOpen) dialogRef.current?.showModal();
_10
}, [isOpen]);

Common pitfalls

#
  • Expecting a re-render. Changing ref.current does not re-render. If the screen should update when an element appears, store something in state, often via a callback ref.
  • Putting ref.current in a dependency list. It is read during render, before the ref updates, so the effect will not rerun when the node changes. Use a callback ref.
  • Null checks in TypeScript. useRef<HTMLDivElement>(null) gives a RefObject whose current can be null. Keep the ?. or an if, rather than a ! assertion that hides real bugs.
  • Using useRef() with no argument. React 19's types require an initial value, so pass null for DOM refs.
  • Refs inside lists. One ref object can only hold one node. For many items, use a callback ref that stores each node in a Map keyed by id.
#

Was this resource helpful?