Skip to content

Commit 8d3b7e5

Browse files
hodanooriCopilot
andauthored
fix(heureka): store shouldExpire predicate in a ref to prevent timer reset on re-renders
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
1 parent b3519c6 commit 8d3b7e5

1 file changed

Lines changed: 10 additions & 2 deletions

File tree

apps/heureka/src/utils.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,13 +131,21 @@ export function useTimedState<T>(
131131
shouldExpire?: (value: T) => boolean
132132
): [T | null, Dispatch<SetStateAction<T | null>>] {
133133
const [value, setValue] = useState<T | null>(null)
134+
const shouldExpireRef = useRef<typeof shouldExpire>()
135+
136+
// Keep the ref updated with the latest predicate without tying the timer effect
137+
// to the predicate's identity (which may change across renders).
138+
useEffect(() => {
139+
shouldExpireRef.current = shouldExpire
140+
}, [shouldExpire])
134141

135142
useEffect(() => {
136143
if (value === null) return
137-
if (shouldExpire && !shouldExpire(value)) return
144+
const predicate = shouldExpireRef.current
145+
if (predicate && !predicate(value)) return
138146
const timer = setTimeout(() => setValue(null), duration)
139147
return () => clearTimeout(timer)
140-
}, [value, duration, shouldExpire])
148+
}, [value, duration])
141149

142150
return [value, setValue]
143151
}

0 commit comments

Comments
 (0)