Skip to content

Instantly share code, notes, and snippets.

@itsMapleLeaf
Last active August 29, 2023 21:31
Show Gist options
  • Save itsMapleLeaf/7189dc39b4d35af2df95fad249ed46ab to your computer and use it in GitHub Desktop.
Save itsMapleLeaf/7189dc39b4d35af2df95fad249ed46ab to your computer and use it in GitHub Desktop.
React useDebouncedCallback
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)
}}
/>
)
}
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