Skip to content

Commit 193015d

Browse files
committed
Fix some useInterval issues
1 parent f544ab2 commit 193015d

1 file changed

Lines changed: 13 additions & 6 deletions

File tree

apps/webapp/app/hooks/useInterval.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useEffect } from "react";
1+
import { useEffect, useRef } from "react";
22

33
type UseIntervalOptions = {
44
/** If passed, will refresh every interval MS */
@@ -16,12 +16,19 @@ export function useInterval({
1616
disabled = false,
1717
callback,
1818
}: UseIntervalOptions) {
19+
// Always keep the latest callback in a ref so the effects below
20+
// never close over a stale version.
21+
const latestCallback = useRef(callback);
22+
useEffect(() => {
23+
latestCallback.current = callback;
24+
}, [callback]);
25+
1926
// On interval
2027
useEffect(() => {
2128
if (!interval || interval <= 0 || disabled) return;
2229

2330
const intervalId = setInterval(() => {
24-
callback();
31+
latestCallback.current();
2532
}, interval);
2633

2734
return () => clearInterval(intervalId);
@@ -33,7 +40,7 @@ export function useInterval({
3340

3441
const handleFocus = () => {
3542
if (document.visibilityState === "visible") {
36-
callback();
43+
latestCallback.current();
3744
}
3845
};
3946

@@ -50,7 +57,7 @@ export function useInterval({
5057

5158
// On load
5259
useEffect(() => {
53-
if (disabled) return;
54-
callback();
55-
}, []);
60+
if (disabled || !onLoad) return;
61+
latestCallback.current();
62+
}, [disabled, onLoad]);
5663
}

0 commit comments

Comments
 (0)