Install all hooks via:
npm install @styple/hooks
or copy the source:
import { useEffect, useRef, useState } from "react";
export const useDebounce = (
callback: () => void,
initialValue: any,
delay: number
) => {
// To prevent calling the callback function on component mount
const didMountRef = useRef<boolean>(false);
const [state, setState] = useState<typeof initialValue>(initialValue);
useEffect(() => {
let delayDebounceFn: NodeJS.Timeout;
if (didMountRef.current) {
delayDebounceFn = setTimeout(callback, delay);
} else {
didMountRef.current = true;
}
return () => clearTimeout(delayDebounceFn);
}, [state, callback]);
return [state, setState];
};