Sub topic 8
Using refs inside effects and cleanup
This chapter covers how refs and useEffect work together. It assumes you know JavaScript closures, function components and JSX, useState, the basic shape of useEffect(setup, deps), and what ref.current is. The rules for reading and writing ref.current during rendering are in the previous chapter.
Why effects are the right place for refs
React renders a component in two phases. During the render phase it calls your function and builds a description of the UI. During the commit phase it updates the DOM, attaches refs, and then runs effects.
By the time an effect runs, every ref prop in the committed tree has been set. A DOM ref that was null during the first render now holds its node. This is why effects and event handlers are the two places where reading ref.current is safe.
The sequence below shows one mount and one unmount.
On mount, the ref is attached before your setup function runs. On unmount, your cleanup runs first and the ref is cleared afterward. The cleanup order matters in the next sections.
Reading a DOM ref in an effect
Use an effect when a DOM node must be kept in sync with props or state. A video element is a typical case, because play() and pause() are imperative methods with no matching attribute.
import { useEffect, useRef } from 'react';
export function VideoPlayer({ src, isPlaying }) {
const videoRef = useRef(null);
useEffect(() => {
const video = videoRef.current;
if (video === null) return;
if (isPlaying) {
video.play().catch(() => {
// Browsers may block playback until the user interacts with the page.
});
} else {
video.pause();
}
}, [isPlaying]);
return <video ref={videoRef} src={src} loop playsInline />;
}The effect depends on isPlaying, which is state or a prop, not on videoRef. The component describes what should be true, and the effect makes the DOM match.
The null check is cheap protection. If the <video> is later wrapped in a condition such as {show && <video ref={videoRef} />}, the ref can be null when the effect runs.
Refs do not belong in the dependency array
A ref object returned by useRef is the same object on every render. Listing it in the dependency array does nothing. React's lint rule knows this and does not require it.
The other direction matters more. Changing ref.current does not re-run an effect, because React does not watch it. If an effect must react to a value changing, that value belongs in state or props, and it belongs in the dependency array. A ref only holds something the effect reads when it runs.
| You want the effect to... | Put the value in... |
|---|---|
| Re-run when the value changes | State or props, listed in the dependencies |
| Read the value but not re-run on changes | A ref, read inside the effect or handler |
| Use a DOM node | A ref, read inside the effect |
Setup and cleanup with a DOM node
Many browser APIs need a node and need to be undone later: observers, event listeners, and third-party widgets. The setup reads the ref and the cleanup undoes what the setup did.
import { useEffect, useRef, useState } from 'react';
export function SizeReporter() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);
useEffect(() => {
const node = boxRef.current;
if (node === null) 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', border: '1px solid' }}>
Width: {width}px
</div>
);
}The width is displayed, so it lives in state. The node is only used to wire up the observer, so it lives in a ref. The effect copies boxRef.current into a local node variable. The cleanup does not need the node here, because it uses observer. When a cleanup does need the node, such as node.removeEventListener(...), it should use the local copy.
Why the local copy matters
Recall the order from the diagram: cleanup runs first, then the ref is set to null. That is the safe case. The risky case is an effect that re-runs while the component stays mounted. If the ref points to a different element by the time the old cleanup runs, boxRef.current in the cleanup is the new node, not the one you set up with.
The React lint rule react-hooks/exhaustive-deps warns about this. If your cleanup reads ref.current for a ref that your component never assigns, you will see a message that the ref value "will likely have changed by the time this effect cleanup function runs". The fix is the local variable:
import { useEffect, useRef } from 'react';
export function ClickLogger({ onOutsideClick }) {
const panelRef = useRef(null);
useEffect(() => {
const panel = panelRef.current;
if (panel === null) return;
function handleClick(event) {
if (!panel.contains(event.target)) {
onOutsideClick();
}
}
document.addEventListener('click', handleClick);
return () => document.removeEventListener('click', handleClick);
}, [onOutsideClick]);
return <div ref={panelRef}>Click outside this panel</div>;
}Here panel is captured once and both the handler and the cleanup agree on which element they belong to. Note that onOutsideClick is in the dependency array. If the parent passes a new function every render, this effect re-subscribes every render. The last chapter of this tutorial covers the latest-callback pattern, which avoids that.
Timer IDs in refs, cleared in cleanup
A timer ID is a value you need later but never display. That makes it a good fit for a ref. The setup starts the timer and the cleanup cancels it, so nothing fires after the component is gone.
This debounced draft saver stores the pending timeout in a ref:
import { useEffect, useRef, useState } from 'react';
export function DraftEditor({ onSave }) {
const [text, setText] = useState('');
const timeoutRef = useRef(null);
function handleChange(event) {
const next = event.target.value;
setText(next);
clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => onSave(next), 500);
}
useEffect(() => {
return () => clearTimeout(timeoutRef.current);
}, []);
return <textarea value={text} onChange={handleChange} />;
}Each keystroke cancels the previous timer and starts a new one. The effect has no setup work. It exists only to clear the last pending timer on unmount.
Reading timeoutRef.current inside the cleanup is correct here. You want the latest timer ID, not the one from when the effect ran. The lint rule does not warn in this case, because the component assigns timeoutRef.current itself. The warning is aimed at DOM refs that React assigns.
Strict Mode: your cleanup runs early in development
In development, React's Strict Mode mounts each component, runs its effect setup, runs the cleanup, and then runs the setup again. This is meant to expose cleanups that are missing or wrong.
For ref-based code, this means any state you keep in a ref must survive a cleanup and be set up again correctly. Consider the stopwatch from earlier in this tutorial, which guards start with if (intervalRef.current !== null) return;. Its cleanup clears the interval, but if it did not also set intervalRef.current = null, a later start would be blocked by a stale ID. Reset the ref when you clear what it points to:
useEffect(() => {
return () => {
clearInterval(intervalRef.current);
intervalRef.current = null;
};
}, []);A good test is to ask what the component looks like after setup, cleanup, setup. If it looks the same as after one setup, your effect is correctly paired.
Writing to refs from effects
Writing ref.current inside an effect is allowed, because effects run outside rendering. A common use is remembering a value from the previous render:
import { useEffect, useRef } from 'react';
export function usePrevious(value) {
const previous = useRef(undefined);
useEffect(() => {
previous.current = value;
});
return previous.current;
}During a render, the hook returns previous.current, which still holds the value from the last committed render. After the commit, the effect updates the ref to the current value. This works because the effect runs after the return value has been computed. Note that the returned value is only as fresh as the last render, and it does not cause a re-render by itself.
Common mistakes in this area
- Reading a DOM ref during render. On the first render it is
null, soref.current.focus()in the function body throws. Move the call into an effect or an event handler. - Expecting an effect to re-run when
ref.currentchanges. It will not. Use state if the change must trigger work. - Using
ref.currentin cleanup for a DOM node without a local copy. Capture the node in a variable in the setup. - Skipping cleanup for timers and listeners. Strict Mode will often expose this as duplicate timers or doubled handlers.
- Forgetting to reset a ref guard in cleanup. A leftover non-null value can block the next setup.
Exercise
A component has const inputRef = useRef(null) and the line inputRef.current.focus() directly in the function body, before the return. It throws "Cannot read properties of null" on first render. Why, and where should the call go so the input is focused after mount?
Show answer
During the first render React has not yet created the DOM node or attached it, so inputRef.current is still null. Refs are attached in the commit phase, before effects run. Move the call into useEffect(() => { inputRef.current.focus(); }, []); (or an event handler). Either place runs after the ref is set.
Exercise
An effect adds a scroll listener to a node held in listRef.current, and its cleanup calls listRef.current.removeEventListener(...). What can go wrong, and how do you fix it?
Show answer
If the effect re-runs while the ref points to a different element, the cleanup reads the new node and tries to remove the listener from the wrong element. The old listener stays attached. Fix it by copying const list = listRef.current; in the setup and using list in both addEventListener and the cleanup's removeEventListener.