Skip to content

useDebouncedState

Debounces state changes

Import

import {useDebouncedState} from '@kaiverse/k/hooks'

Usage

useDebouncedState hook debounces state value changes. The state will be updated after the delay time has passed since the last setState call.

Playground

Debounced state value: empty

some-component.tsx
import {useDebouncedState} from '@kaiverse/k/hooks'
export default function SomeComponent() {
const [value, setValue] = useDebouncedState('', 200)
return (
<>
<input
placeholder="Type something to see debounce state update"
type="text"
defaultValue={value}
onChange={(event) => setValue(event.currentTarget.value)}
/>
<p>Debounced state value: {value}</p>
</>
)
}

Immediately update state

You can immediately update state with first setState call by passing true as the third argument.

Playground

Debounced state value: empty

some-component.tsx
const [value, setValue] = useDebouncedState('', 200, true)

Type definition

function useDebouncedState<T>(
defaultValue: T,
debounceTime: number, // ms
updateFirstChange = false,
): Readonly<[T, React.Dispatch<React.SetStateAction<T>>]>