Skip to content

useWatch

Category
Export Size
176 B
Last Changed
5 days ago

Watches a source — a single value or an array of values — and invokes a callback with (value, oldValue) whenever it changes

Demo

Usage

tsx
import { 
useWatch
} from '@reause/shared'
useWatch
(count, (
value
,
oldValue
) => {
console
.
log
(
value
,
oldValue
)
}) // array source — fires when any element changes
useWatch
([count,
name
], (
value
,
oldValue
) => {
console
.
log
(
value
,
oldValue
)
})

Options

NameTypeDefaultDescription
immediatebooleanfalseFire the callback once on mount with the current value

With immediate: true the callback fires on mount with (value, undefined), then with (value, oldValue) on every subsequent change:

tsx
useWatch
(count, (
value
,
oldValue
) => {
console
.
log
(
value
,
oldValue
) // (0, undefined) on mount, then (1, 0), ...
}, {
immediate
: true })

Type Declarations

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

export interface UseWatchOptions {
    immediate?: boolean;
}

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

Contributors

hairyf

Changelog

v0.1.0 on
143e8 - fix(shared): resolve useWatch audit findings (#761)

Released under the MIT License. v0.1.8