Skip to content

Instantly share code, notes, and snippets.

@hamzakaya
Created October 28, 2021 11:19
Show Gist options
  • Save hamzakaya/ebc369b6a1013fa81c4aceea09d6d083 to your computer and use it in GitHub Desktop.
Save hamzakaya/ebc369b6a1013fa81c4aceea09d6d083 to your computer and use it in GitHub Desktop.
import { useEffect, useState, useRef } from 'react';
export function useDebouncedValue<T = any>(value: T, wait: number, options = { leading: false }) {
const [_value, setValue] = useState(value);
const mountedRef = useRef(false);
const timeoutRef = useRef<number>(null);
const cooldownRef = useRef(false);
const cancel = () => window.clearTimeout(timeoutRef.current);
useEffect(() => {
if (mountedRef.current) {
if (!cooldownRef.current && options.leading) {
cooldownRef.current = true;
setValue(value);
} else {
cancel();
timeoutRef.current = window.setTimeout(() => {
cooldownRef.current = false;
setValue(value);
}, wait);
}
}
}, [value, options.leading]);
useEffect(() => {
mountedRef.current = true;
return cancel;
}, []);
return [_value, cancel] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment