Skip to content

useWatchPausable

Category
Export Size
310 B
Last Changed
5 days ago

Pausable watch — pause and resume a watched value's updates

Demo

Usage

Watch your own state value; the returned controls carry extra pause() and resume() functions to control the callback.

tsx
import { 
useWatchPausable
} from '@reause/shared'
import {
useState
} from 'react'
const [
value
,
setValue
] =
useState
('foo')
const {
pause
,
resume
,
stop
} =
useWatchPausable
(
value
,
v
=>
console
.
log
(`Changed to ${
v
}!`),
)
setValue
('bar') // logs: Changed to bar!
pause
()
setValue
('foobar') // (nothing logged — the change is dropped while paused)
resume
()
setValue
('hello') // logs: Changed to hello!

Start paused and fire once on mount with initialState / immediate:

tsx
import { 
useWatchPausable
} from '@reause/shared'
import {
useState
} from 'react'
const [
value
,
setValue
] =
useState
('foo')
const {
isActive
} =
useWatchPausable
(
value
,
v
=>
console
.
log
(`Changed to ${
v
}!`),
{
initialState
: 'paused' },
)

Options

OptionTypeDefaultDescription
initialState'active' | 'paused''active'The initial state of the watcher
immediatebooleanfalseFire the callback once on mount with the current value

Type Declarations

ts
export interface UseWatchPausableOptions {
    initialState?: 'active' | 'paused';
    immediate?: boolean;
}

export interface UseWatchPausableReturn {
    pause: () => void;
    resume: () => void;
    isActive: boolean;
    stop: () => void;
}

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

export function useWatchPausable<T extends any[]>(source: readonly [
    ...T
], callback: UseWatchCallback<[
    ...T
]>, options?: UseWatchPausableOptions): UseWatchPausableReturn

export function useWatchPausable<T>(source: T, callback: UseWatchCallback<NoInfer<T>>, options?: UseWatchPausableOptions): UseWatchPausableReturn

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
2a882 - fix(shared): resolve useWatchPausable audit findings (#772)

Released under the MIT License. v0.1.8