Skip to content

Instantly share code, notes, and snippets.

@mattrossman
Created April 12, 2024 21:08
Show Gist options
  • Save mattrossman/859ed89145707ee9926475902f106b53 to your computer and use it in GitHub Desktop.
Save mattrossman/859ed89145707ee9926475902f106b53 to your computer and use it in GitHub Desktop.
useFuse
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