Skip to content

useStateDebounced

Category
Export Size
1.08 kB
Last Changed
5 days ago

A controllable state which will be debounced.

Demo

Usage

tsx
import { 
useStateDebounced
} from '@reause/shared'
const [
input
,
setInput
,
debounced
] =
useStateDebounced
('foo', 1000)
setInput
('bar')
console
.
log
(
debounced
) // 'foo' — flips to 'bar' once the debounce elapses

Use an existing state tuple when the source is owned by the parent component:

tsx
const 
state
=
useState
('foo')
const [
input
,
setInput
,
debounced
] =
useStateDebounced
(
state
, 1000)

For controlled state, updates are sent to onChange and the debounced value follows the controlled value after the delay:

tsx
const [
input
,
setInput
,
debounced
] =
useStateDebounced
(
{
value
,
onChange
: setValue },
300, )

An example with an object value.

tsx
import { 
useStateDebounced
} from '@reause/shared'
const [
data
,
setData
,
debounced
] =
useStateDebounced
({
name
: 'foo',
age
: 18,
}, 1000) function
update
() {
setData
({
...
data
,
name
: 'bar',
}) }
console
.
log
(
debounced
) // { name: 'foo', age: 18 }
update
()
await sleep(1100)
console
.
log
(
debounced
) // { name: 'bar', age: 18 }

You can also pass an optional 3rd parameter including the maxWait option. See useDebounceFn for details.

Type Declarations

ts
export type UseStateDebouncedReturn<T = any> = [
    value: T,
    setValue: Dispatch<SetStateAction<T>>,
    debounced: T
]

export type State<T> = StateValue<T>

export interface DebounceFilterOptions {
    maxWait?: number;
    rejectOnCancel?: boolean;
}

export function useStateDebounced<T>(value: State<T>, ms?: number, options?: DebounceFilterOptions): UseStateDebouncedReturn<T>

export function useControllableState<T>(state: State<T>, options?: UseControllableStateOptions<T>): StateTuple<T>

export function useDebounceFn<T extends FunctionArgs>(fn: T, ms?: number, options?: DebounceFilterOptions): UseDebounceFnReturn<T>

Source

Source · Demo

Contributors

hairyf

Changelog

v0.1.0 on
1d3ef - fix(shared): resolve useStateDebounced audit findings (#743)
67e98 - feat(shared): add useStateDebounced (#50)

Released under the MIT License. v0.1.8