Sub topic 9
Common pitfalls with useRef
This chapter assumes you know JavaScript closures, function components and JSX, useState and re-rendering, and basic useEffect. It also assumes you know what a ref is, how useRef returns a { current } object, and how to attach one to a DOM element. Here you will learn the mistakes that come up most often and how to fix each one.
Reading ref.current before it exists
React fills a DOM ref after it commits the element to the page. During the first render, ref.current is still the initial value, usually null. Code that touches it too early throws.
import { useRef } from 'react';
export function Broken() {
const inputRef = useRef(null);
// TypeError: Cannot read properties of null
inputRef.current.focus();
return <input ref={inputRef} />;
}Move the call to a place that runs after the commit: an event handler or an effect.
import { useEffect, useRef } from 'react';
export function AutoFocus() {
const inputRef = useRef(null);
useEffect(() => {
inputRef.current?.focus();
}, []);
return <input ref={inputRef} />;
}The same rule applies later in the component's life. If an element is rendered conditionally, its ref becomes null again when the element unmounts. Use optional chaining or an explicit check whenever the element might not be on the screen.
Touching ref.current during render
A component body should be a pure calculation of JSX from props and state. Reading or writing ref.current there makes the output depend on something React does not track.
import { useRef } from 'react';
export function RenderCounter() {
const renders = useRef(0);
renders.current += 1; // impure write during render
return <p>Rendered {renders.current} times</p>;
}This looks harmless, but React may render a component more than once without committing. Strict Mode in development does this on purpose, so the count above jumps by two. Concurrent rendering can also discard a render. The number then no longer matches what actually reached the screen.
The one accepted exception is lazy initialization: setting ref.current once when it is still null, as in the Map example from the lazy initialization chapter. Everything else belongs in handlers and effects.
Using a ref for data that appears on screen
Changing ref.current does not cause a re-render. If the value is shown in the JSX, the screen will not update.
import { useRef } from 'react';
export function ClickCounter() {
const count = useRef(0);
return (
<button
onClick={() => {
count.current += 1;
}}
>
Clicked {count.current} times
</button>
);
}The value increases on every click, but the button text stays at 0 until something else triggers a render. The fix is state.
import { useState } from 'react';
export function ClickCounter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount((c) => c + 1)}>Clicked {count} times</button>;
}A quick test: if a change to the value should change what the user sees, it is state. If the value only matters to code you run later, such as a timer ID or a DOM node, it can be a ref.
Expecting a ref change to run an effect
Refs are not reactive. Putting ref.current in a dependency array does not do what it appears to do.
useEffect(() => {
console.log('width changed');
}, [boxRef.current?.offsetWidth]); // evaluated during render, not on changeReact compares dependencies only when the component renders. If the width changes without a render, the effect does not run. If it happens to render later, the effect sees whatever the value was at that moment. When you need to react to a size change, subscribe to it with a ResizeObserver inside an effect, and store the result in state if the UI depends on it.
Reading a ref in cleanup
By the time a cleanup function runs, ref.current may already point to something else, or to null. Copy the node into a local variable when the effect starts and use that variable in the cleanup.
import { useEffect, useRef, useState } from 'react';
export function MeasuredBox() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const node = boxRef.current;
if (!node) return;
const observer = new ResizeObserver(([entry]) => {
setWidth(Math.round(entry.contentRect.width));
});
observer.observe(node);
return () => observer.disconnect();
}, []);
return (
<div ref={boxRef} style={{ resize: 'horizontal', overflow: 'auto' }}>
Width: {width}px
</div>
);
}Here the effect needs the node only once, so an empty dependency array is correct. The width is stored in state because it is displayed.
Forgetting to clean up what a ref holds
A timer ID stored in a ref is easy to lose track of. If the component unmounts while the interval is running, the callback keeps firing and tries to update a component that is gone. Always pair the setup with a cleanup in an effect.
useEffect(() => {
return () => clearInterval(intervalRef.current);
}, []);Strict Mode helps here. In development React mounts, unmounts, and mounts the component again. A missing cleanup then shows up immediately as two timers running at once.
Refs and custom components
Passing ref to your own component does not give you a DOM node unless the component forwards it. In React 18 and earlier, ref is not passed as a prop at all. The parent's ref stays null, and React logs a warning. The component must be wrapped in forwardRef.
import { forwardRef } from 'react';
const TextField = forwardRef(function TextField(props, ref) {
return <input ref={ref} {...props} />;
});In React 19, function components receive ref as an ordinary prop, so no wrapper is needed.
function TextField({ ref, ...props }) {
return <input ref={ref} {...props} />;
}If your project's React version is unclear, check package.json before choosing a form. Forwarding the raw node also lets the parent do anything to it. When that is too much access, expose a narrow API with useImperativeHandle, as covered in the previous chapter.
Refs in loops
Hooks cannot be called inside loops, conditions, or map callbacks. This code breaks the Rules of Hooks:
{items.map((item) => {
const ref = useRef(null); // not allowed
return <li key={item.id} ref={ref}>{item.title}</li>;
})}Use one ref that holds a Map, filled by callback refs, as in the list example from the callback refs chapter. A callback ref runs with the node on mount and with null on unmount, so the Map stays in sync with the list.
One more detail: an inline callback ref is a new function on every render. React calls the old one with null and the new one with the node each time. That is harmless for a Map that gets set and deleted, but it matters if the callback does expensive work. In that case, define the function once with useCallback.
Editing DOM that React manages
A ref gives you permission to call methods like focus, scrollIntoView, and getBoundingClientRect. It does not give you permission to change the structure React is rendering. Removing a child, replacing text, or adding classes that React also sets can leave the page out of step with React's records. The next render may then throw, for example when React tries to remove a node that no longer exists.
Safe uses are actions that do not alter React's output: focus, scroll, measure, play or pause media, and call APIs of third-party widgets. If you need to change what is displayed, change state or props.
Summary of symptoms
| Symptom | Likely cause | Fix |
|---|---|---|
| `Cannot read properties of null` | Reading `ref.current` before mount or after unmount | Move to an effect or handler, use `?.` |
| Value changes but screen does not | Displayed data stored in a ref | Use state |
| Count jumps by two in development | Writing to a ref during render under Strict Mode | Write in a handler or effect |
| Parent ref is `null` on a custom component | Component does not forward `ref` | `forwardRef` or React 19 `ref` prop |
| Effect never reruns when a ref changes | Ref in dependency array | Subscribe in an effect, store result in state |
| Two timers after mount in development | Missing cleanup | Clear in the effect's return function |
A debugging path for a null ref
Work through the branches in order. Most null refs are explained by the first two questions.
Exercise
A component keeps const total = useRef(0), adds to total.current inside a click handler, and shows total.current in its JSX. The number on screen never changes. Why, and what is the fix?
Show answer
Changing ref.current does not trigger a re-render, so React never produces new JSX with the updated number. Because the value is displayed, it should be state: const [total, setTotal] = useState(0) and setTotal((t) => t + 1) in the handler.
Exercise
This effect runs after mount: useEffect(() => { const node = boxRef.current; node.addEventListener('scroll', onScroll); return () => boxRef.current.removeEventListener('scroll', onScroll); }, []);. Name the pitfall in the cleanup and rewrite the cleanup.
Show answer
The cleanup reads boxRef.current, which may be null or a different node by the time cleanup runs. Use the node captured when the effect started: return () => node.removeEventListener('scroll', onScroll);. A guard such as if (!node) return; at the top of the effect also protects the setup from a missing node.