Ref cleanup runs twice or for the wrong element when a callback ref is reused
Author: gengjiawenCreated Sep 29, 2026Updated Sep 29, 2026
- Check if updating to the latest Preact version resolves the issue
Describe the bug
A callback ref can return a cleanup function (#4436). applyRef keeps that cleanup on the ref function itself (ref._unmount) and doesn't clear it after calling it. A ref function isn't tied to one element, though: it can be attached again after an unmount, or to several elements at once. So cleanups run twice, or for the wrong element:
- The same ref is mounted again after an unmount. The old cleanup runs a second time, right before the ref is called with the new element.
- One ref is shared by several elements, e.g.
ref={observe}on every item of a list. Attaching the second element runs the first element's cleanup while it is still mounted. On unmount, the last element's cleanup runs once per element and the others never run. - The element is inside a Suspense boundary that suspends again (
mainonly). The cleanup runs when the subtree is parked, and again when it is revealed.
Reproduced on 10.29.8 (latest), 11.0.0-rc.2 and main (553b3fe). Refs on class components under preact/compat behave the same way.
To Reproduce
import { h, render } from 'preact';
let log = [];
const makeRef = () => el => {
log.push(`ref ${el.textContent}`);
return () => log.push(`cleanup ${el.textContent}`);
};
const root = document.body.appendChild(document.createElement('div'));
// 1. The same ref, mounted again after an unmount
const ref = makeRef();
render(h('p', { ref }, 'A'), root);
render(null, root);
render(h('p', { ref }, 'B'), root);
console.log(log);
// ['ref A', 'cleanup A', 'cleanup A', 'ref B']
// 2. One ref shared by two elements
render(null, root);
log = [];
const shared = makeRef();
render(h('ul', null, h('li', { ref: shared }, 'A'), h('li', { ref: shared }, 'B')), root);
render(null, root);
console.log(log);
// ['ref A', 'cleanup A', 'ref B', 'cleanup B', 'cleanup B']Expected behavior
Each cleanup runs once, when its own element is detached:
['ref A', 'cleanup A', 'ref B']['ref A', 'ref B', 'cleanup A', 'cleanup B']
React 19.3 logs exactly this for the same code. It keeps the cleanup on the fiber (refCleanup), not on the ref function.
Source: preactjs/preact