|
1 | | -import { useEffect, useId, useRef } from "react"; |
| 1 | +import { useEffect, useEffectEvent, useId } from "react"; |
2 | 2 |
|
3 | 3 | export const LIVE_REFRESH_MIN_INTERVAL_MS = 10_000; |
4 | 4 |
|
@@ -83,20 +83,19 @@ export function useLiveRefresh( |
83 | 83 | } = {}, |
84 | 84 | ): void { |
85 | 85 | const { enabled = true, key, intervalMs = LIVE_REFRESH_INTERVAL_MS } = options; |
86 | | - // Held in a ref so a caller can pass a fresh closure every render without re-arming the |
| 86 | + // An effect event so a caller can pass a fresh closure every render without re-arming the |
87 | 87 | // listeners, which would otherwise refresh on every render that changed anything at all. |
88 | | - const latest = useRef(refresh); |
89 | | - latest.current = refresh; |
| 88 | + const runRefresh = useEffectEvent((viewId: string, now: number) => { |
| 89 | + if (refresh === null) return; |
| 90 | + lastRefreshedAtByView.set(viewId, now); |
| 91 | + refresh(); |
| 92 | + }); |
90 | 93 | const fallbackViewId = useId(); |
91 | 94 | const viewId = key ?? fallbackViewId; |
92 | 95 |
|
93 | 96 | useEffect(() => { |
94 | 97 | if (!enabled) return; |
95 | | - const read = (now: number) => { |
96 | | - if (latest.current === null) return; |
97 | | - lastRefreshedAtByView.set(viewId, now); |
98 | | - latest.current(); |
99 | | - }; |
| 98 | + const read = (now: number) => runRefresh(viewId, now); |
100 | 99 | const visible = () => document.visibilityState === "visible"; |
101 | 100 | const onArrival = () => { |
102 | 101 | const now = Date.now(); |
|
0 commit comments