Sub topic 8
Using refs inside effects and cleanup
This chapter assumes you know useState, basic useEffect with a dependency array, and the idea that a ref is a container whose .current survives renders. Here you will see when it is safe to read a ref in an effect, and how to handle cleanup.
Why effects are the right place for refs
React attaches DOM refs while it commits a render. Effects run after the commit. So inside an effect, ref.current already points to the DOM node, while during the first render it is still null.
Event handlers are the other safe place. Both run outside rendering, so they do not break render purity.
Subscribing to a DOM node
A common job is adding a listener to an element you hold a ref to. Copy ref.current into a local variable at the start of the effect. The cleanup then removes the listener from the same node that received it.
import { useEffect, useRef } from 'react';
export function Panel() {
const panelRef = useRef(null);
useEffect(() => {
const node = panelRef.current;
if (node === null) return;
function handleScroll() {
console.log('scrollTop:', node.scrollTop);
}
node.addEventListener('scroll', handleScroll);
return () => node.removeEventListener('scroll', handleScroll);
}, []);
return (
<div ref={panelRef} style={{ height: 100, overflow: 'auto' }}>
<div style={{ height: 400 }}>Scroll me</div>
</div>
);
}The null check is cheap protection. If the element is rendered conditionally, the ref can be empty when the effect runs.
Reading a ref in cleanup
The react-hooks/exhaustive-deps lint rule warns when a cleanup function reads ref.current. For a DOM ref, the warning is right. By the time cleanup runs, React may have set ref.current to null or pointed it at a different node. That is why the previous example captured node first.
For a ref that holds a non-visual value such as a timer ID, the situation is reversed. You want the latest value at cleanup time, because the ID may have changed since the effect ran.
import { useEffect, useRef, useState } from 'react';
export function Ticker() {
const [ticks, setTicks] = useState(0);
const intervalRef = useRef(null);
useEffect(() => {
intervalRef.current = setInterval(() => {
setTicks((t) => t + 1);
}, 1000);
return () => {
clearInterval(intervalRef.current);
intervalRef.current = null;
};
}, []);
function pause() {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
return (
<div>
<p>{ticks}s</p>
<button onClick={pause}>Pause</button>
</div>
);
}If pause runs first, cleanup finds null and clearInterval(null) does nothing. If it did not, cleanup would clear the interval. Either way, no timer leaks.
Rules of thumb
| Ref holds | Read in effect | Read in cleanup |
|---|---|---|
| DOM node | Yes, after the null check | Use a local copy taken in the effect |
| Timer ID or other instance value | Yes | Yes, you usually want the latest value |
Don't rely on a ref to trigger an effect
Putting ref.current in a dependency array does not work as intended. Changing a ref does not cause a render, so React never re-checks the array. If a change must re-run an effect, keep that value in state.
Exercise
A component adds a resize listener inside an effect to a <div> held in boxRef. The cleanup calls boxRef.current.removeEventListener(...). Why can this fail, and what is the fix?
Show answer
By the time cleanup runs, React may have set boxRef.current to null (on unmount) or to another node, so the call can throw or remove from the wrong element. Fix it by saving const node = boxRef.current; at the start of the effect and using node in both addEventListener and the cleanup.