Skip to content

useWatchThrottled

Category
Export Size
558 B
Last Changed
5 days ago

Throttled watch. The callback will be invoked at most once per specified duration

Demo

Usage

Similar to useWatch, but offering extra options throttle, trailing, and leading which will be applied to the callback function.

tsx
import { 
useWatchThrottled
} from '@reause/shared'
useWatchThrottled
(
input, () => {
console
.
log
('changed!') },
{
throttle
: 500 },
)

Options

OptionTypeDefaultDescription
throttlenumber0Throttle interval in ms
trailingbooleantrueInvoke on the trailing edge
leadingbooleantrueInvoke on the leading edge
immediatebooleanfalseFire the callback once on mount with the current value (still throttled)

Leading and Trailing

Control when the callback is invoked:

tsx
import { 
useWatchThrottled
} from '@reause/shared'
// Only invoke at the start of each throttle period
useWatchThrottled
(source, callback, {
throttle
: 500,
leading
: true,
trailing
: false,
}) // Only invoke at the end of each throttle period
useWatchThrottled
(source, callback, {
throttle
: 500,
leading
: false,
trailing
: true,
})

Fire the callback once on mount with the current value (still throttled):

tsx
import { 
useWatchThrottled
} from '@reause/shared'
useWatchThrottled
(input, () =>
console
.
log
('changed!'), {
immediate
: true })

Type Declarations

ts
export interface UseWatchThrottledOptions {
    throttle?: number;
    trailing?: boolean;
    leading?: boolean;
    immediate?: boolean;
}

export interface UseWatchCallback<T = any> {
    (value: T, oldValue: T | undefined): void;
}

export function useWatchThrottled<T extends any[]>(source: readonly [
    ...T
], callback: UseWatchCallback<[
    ...T
]>, options?: UseWatchThrottledOptions): void

export function useWatchThrottled<T>(source: T, callback: UseWatchCallback<T>, options?: UseWatchThrottledOptions): void

export function useWatch<T extends any[]>(source: readonly [
    ...T
], callback: UseWatchCallback<[
    ...T
]>, options?: UseWatchOptions): void

export function useWatch<T>(source: T, callback: UseWatchCallback<T>, options?: UseWatchOptions): void

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
7c176 - fix(shared): resolve useWatchThrottled audit findings (#773)
8fddc - chore!: remove all Vue-only Maybe* types and getter unions, adopt React Ref (#462)

Released under the MIT License. v0.1.8