Sub topic 3
React `useRef`: Common Pitfalls and Advanced Patterns
Assume you know JavaScript closures, function components, JSX, useState, useEffect, and basic DOM APIs.
Common pitfalls
A ref is not state. Changing ref.current does not schedule a render, so do not store text or values that must appear on screen in a ref. Use state for those values.
A DOM ref is also null before the element mounts and after it unmounts. Check it before calling a method. During rendering, avoid reading or changing ref.current. Rendering should stay predictable. Effects and event handlers are the usual places for ref operations.
Callback refs
A callback ref is a function that receives a DOM node when it mounts and null when it unmounts. It is useful when a list contains a changing number of elements.
Passing refs to child components
Refs do not automatically pass through ordinary function components. In React 19, a function component can receive ref as a prop. In earlier React versions, wrap the component with forwardRef.
Lazy initialization of ref contents
useRef(new ExpensiveThing()) evaluates the constructor on every render, even though React keeps only the first value. For expensive, deterministic setup, initialize once:
const thingRef = useRef(null);
if (thingRef.current === null) {
thingRef.current = new ExpensiveThing();
}This is the main safe exception to writing ref.current during rendering. The result must always be the same for that component instance.
Refs for lists of elements
Store nodes in a Map keyed by stable item IDs. A callback ref should add the node and delete it when React supplies null. Avoid an array indexed by position when items can be inserted or reordered.
Exposing a small API
Use useImperativeHandle to expose selected actions instead of the child’s entire DOM node:
const Input = forwardRef(function Input(props, ref) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus: () => inputRef.current?.focus(),
}));
return <input {...props} ref={inputRef} />;
});The latest-callback pattern
An interval can keep calling an old callback if the callback changes after setup. Store the newest callback in a ref, then let an effect create the interval only when its delay changes.
Exercise
Why should a timer ID usually live in a ref instead of state?
Show answer
The ID controls cleanup but does not belong on screen, so changing it does not need a re-render.