Skip to content

Commit 3588d54

Browse files
committed
perf: only cancel the frame on unmount
1 parent 7990ef9 commit 3588d54

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

package/src/hooks/useRafCoalescedValue.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,30 +8,33 @@ import { useEffect, useRef, useState } from 'react';
88
export const useRafCoalescedValue = <S>(value: S): S => {
99
const [emitted, setEmitted] = useState<S>(value);
1010
const pendingRef = useRef<S>(value);
11-
const rafIdRef = useRef<number | 0>(0 as const);
11+
const rafIdRef = useRef<number | null>(null);
1212

1313
// If `value` changes, schedule a single RAF to publish the latest one.
1414
useEffect(() => {
1515
if (value === pendingRef.current) return;
1616
pendingRef.current = value;
1717

18-
if (rafIdRef.current) return; // already scheduled this frame
18+
// already scheduled the next frame, skip
19+
if (rafIdRef.current) return;
1920

2021
const run = () => {
21-
rafIdRef.current = 0;
22+
rafIdRef.current = null;
2223
setEmitted(pendingRef.current);
2324
};
2425

2526
rafIdRef.current = requestAnimationFrame(run);
27+
}, [value]);
2628

29+
useEffect(() => {
2730
return () => {
28-
// cancel the frame if needed
31+
// cancel the frame if it exists only on unmount
2932
if (rafIdRef.current) {
3033
cancelAnimationFrame(rafIdRef.current);
31-
rafIdRef.current = 0;
34+
rafIdRef.current = null;
3235
}
3336
};
34-
}, [value]);
37+
}, []);
3538

3639
return emitted;
3740
};

0 commit comments

Comments
 (0)