Created
February 13, 2024 14:14
-
-
Save KristofferEriksson/2d78b69401be23e05f8b1ac12a998da4 to your computer and use it in GitHub Desktop.
A React Typescript hook that allows you to debounce any fast changing value
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 { useEffect, useState } from "react"; | |
/** | |
* useDebounce hook | |
* This hook allows you to debounce any fast changing value. The debounced value will only | |
* reflect the latest value when the useDebounce hook has not been called for the specified delay period. | |
* | |
* @param value - The value to be debounced. | |
* @param delay - The delay in milliseconds for the debounce. | |
* @returns The debounced value. | |
*/ | |
function useDebounce<T>(value: T, delay: number): { debouncedValue: T } { | |
// State and setters for debounced value | |
const [debouncedValue, setDebouncedValue] = useState(value); | |
useEffect(() => { | |
if (typeof value === "string" && value.trim().length === 0) { | |
setDebouncedValue(value); | |
return; | |
} | |
// Update debounced value after the specified delay | |
const handler = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
// Cancel the timeout if value changes (also on delay change or unmount) | |
// This is how we prevent debounced value from updating if value is changed within the delay period | |
return () => { | |
clearTimeout(handler); | |
}; | |
}, [value, delay]); // Only re-call effect if value or delay changes | |
return { debouncedValue }; | |
} | |
export default useDebounce; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment