Skip to content

Commit cac7061

Browse files
tsengwoodyksen0
authored andcommitted
fix(useLiveRegion): clear pending timers to prevent race conditions & leaks
1 parent 3406f6d commit cac7061

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/components/hooks/useLiveRegion.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,30 @@
1-
import { useRef } from 'preact/hooks';
1+
import { useRef, useEffect } from 'preact/hooks';
22

33
export function useLiveRegion<T extends HTMLElement = HTMLElement>() {
44
const ref = useRef<T | null>(null);
5+
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
6+
7+
/** Clear any existing timer */
8+
const clearTimer = () => {
9+
if (timerRef.current !== null) {
10+
clearTimeout(timerRef.current);
11+
timerRef.current = null;
12+
}
13+
if (ref.current) ref.current.textContent = '';
14+
};
515

616
const announce = (message: string, clearMessage = 1000) => {
717
const node = ref.current;
818
if (!node) return;
19+
clearTimer();
920
node.textContent = message;
10-
setTimeout(() => {
21+
timerRef.current = setTimeout(() => {
1122
if (node) node.textContent = '';
23+
timerRef.current = null;
1224
}, clearMessage);
1325
};
1426

27+
useEffect(() => clearTimer, []);
28+
1529
return { ref, announce };
1630
}

0 commit comments

Comments
 (0)