Created
October 28, 2021 11:19
-
-
Save hamzakaya/ebc369b6a1013fa81c4aceea09d6d083 to your computer and use it in GitHub Desktop.
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 { 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