Skip to content

Instantly share code, notes, and snippets.

@MarekZeman91
Created January 9, 2026 13:23
Show Gist options
  • Select an option

  • Save MarekZeman91/72b4d178144a8fc934494bcaebd8cdbc to your computer and use it in GitHub Desktop.

Select an option

Save MarekZeman91/72b4d178144a8fc934494bcaebd8cdbc to your computer and use it in GitHub Desktop.
import { Dispatch, SetStateAction, useState } from 'react'
import { useConst } from './useConst'
import { useOnUnmount } from './useOnUnmount'
export function useDebouncedState<T>(initialValue: T, delay = 1): [T, Dispatch<SetStateAction<T>>] {
const [debouncedValue, setDebouncedValue] = useState(initialValue)
const api = useConst(() => {
let tempValue = initialValue
let timeout = 0
return {
set: <S extends SetStateAction<T>>(newValue: S) => {
window.clearTimeout(timeout)
tempValue = typeof newValue === 'function' ? newValue(tempValue) : newValue
timeout = window.setTimeout(() => setDebouncedValue(tempValue), delay)
},
cancel: () => window.clearTimeout(timeout),
}
})
useOnUnmount(() => api.cancel())
return [debouncedValue, api.set]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment