Last active
August 29, 2023 21:31
-
-
Save itsMapleLeaf/7189dc39b4d35af2df95fad249ed46ab to your computer and use it in GitHub Desktop.
React useDebouncedCallback
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 { useDebouncedCallback } from "./useDebouncedCallback" | |
export function Example() { | |
const searchDebounced = useDebouncedCallback((query: string) => { | |
// do something with query | |
}, 500) | |
return ( | |
<input | |
onChange={(event) => { | |
searchDebounced(event.target.value) | |
}} | |
/> | |
) | |
} |
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 { useRef, useEffect, useCallback } from "react" | |
export function useDebouncedCallback<Args extends unknown[]>( | |
callback: (...args: Args) => void, | |
period: number, | |
) { | |
// copy the callback to a ref so we always get the latest callback | |
// without needing it as a useCallback dependency below | |
const callbackRef = useRef(callback) | |
useEffect(() => { | |
callbackRef.current = callback | |
}) | |
const timeoutRef = useRef<ReturnType<typeof setTimeout>>() | |
return useCallback( | |
(...args: Args) => { | |
if (timeoutRef.current) { | |
clearTimeout(timeoutRef.current) | |
} | |
timeoutRef.current = setTimeout(() => { | |
callbackRef.current(...args) | |
}, period) | |
}, | |
[period], | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment