Created
August 11, 2024 21:17
-
-
Save Ebrahim-Ramadan/76d96ed8eeb481c016e614e931a19e5f to your computer and use it in GitHub Desktop.
simple use debounce hook in react
This file contains hidden or 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 * as React from "react" | |
export function useDebounce( | |
value | |
delay | |
callback | |
) { | |
const [debouncedValue, setDebouncedValue] = React.useState(value) | |
React.useEffect(() => { | |
const timer = setTimeout(() => { | |
setDebouncedValue(value) | |
callback?.(value) | |
}, delay ?? 500) | |
return () => { | |
clearTimeout(timer) | |
} | |
}, [value, delay, callback]) | |
return debouncedValue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment