Created
April 12, 2024 21:08
-
-
Save mattrossman/859ed89145707ee9926475902f106b53 to your computer and use it in GitHub Desktop.
useFuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useCallback, useEffect, useRef, useState } from "react"; | |
export function useFuse<T>(initialValue: T) { | |
const [value, setValue] = useState<T>(initialValue); | |
const timeoutId = useRef<number>(); | |
const onComplete = useCallback(() => { | |
setValue(initialValue); | |
}, [initialValue]); | |
const trigger = useCallback( | |
(value: T, ms: number) => { | |
setValue(value); | |
window.clearTimeout(timeoutId.current); | |
timeoutId.current = window.setTimeout(onComplete, ms); | |
}, | |
[onComplete], | |
); | |
useEffect(() => { | |
return () => window.clearTimeout(timeoutId.current); | |
}, []); | |
return [value, trigger] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment