Created
January 9, 2026 13:23
-
-
Save MarekZeman91/72b4d178144a8fc934494bcaebd8cdbc to your computer and use it in GitHub Desktop.
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 { 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