Created
January 16, 2024 11:16
-
-
Save hrdyjan1/7d8ff5f4141e26ece3027e65ff6deee3 to your computer and use it in GitHub Desktop.
React solution use debounce
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 {useCallback, useRef} from 'react'; | |
| type BaseFunction = (...args: any[]) => any; | |
| /** | |
| * Custom hook for creating a debounced callback function. | |
| * | |
| * @param {BaseFunction} callback - The callback function to be debounced. | |
| * @param {number} delay - The delay in milliseconds for the debounce. | |
| * | |
| * @returns {BaseFunction} - The debounced callback function. | |
| * | |
| * @example | |
| * // Import the hook | |
| * import { useDebouncedCallback } from 'path-to-file'; | |
| * | |
| * // Usage inside a functional component | |
| * const MyComponent: React.FC = () => { | |
| * const callback = useCallback((param) => { | |
| * // Your callback logic here | |
| * console.log(param); | |
| * }, []); | |
| * | |
| * // Set the desired debounce delay in milliseconds | |
| * const debouncedCallback = useDebouncedCallback(callback, 300); | |
| * | |
| * const handleClick = useCallback(() => debouncedCallback('Click'), [debouncedCallback]); | |
| * | |
| * return ( | |
| * <div> | |
| * <button onClick={handleClick}>Click me (Debounced)</button> | |
| * </div> | |
| * ); | |
| * }; | |
| */ | |
| export function useDebouncedCallback<T extends BaseFunction>(callback: T, delay: number): T { | |
| const timeoutRef = useRef<NodeJS.Timeout | null>(null); | |
| // The debounced callback function created by useDebouncedCallback. | |
| // This function utilizes a setTimeout mechanism to debounce the original callback. | |
| // It prevents the original callback from being invoked immediately on every call, | |
| // instead, it waits for the specified delay between calls before triggering. | |
| const debouncedCallback = useCallback( | |
| (...args: Parameters<T>) => { | |
| const execute = () => { | |
| timeoutRef.current && clearTimeout(timeoutRef.current); | |
| callback(...args); | |
| }; | |
| timeoutRef.current && clearTimeout(timeoutRef.current); | |
| timeoutRef.current = setTimeout(execute, delay); | |
| }, | |
| [callback, delay] | |
| ) as T; | |
| return debouncedCallback; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment