Skip to content

Latest commit

 

History

History
64 lines (54 loc) · 1.91 KB

useDebounce.md

File metadata and controls

64 lines (54 loc) · 1.91 KB

useDebounce

Vue hook that delays invoking a function until after wait milliseconds have elapsed since the last time the debounced function was invoked.

The third argument is the array of values that the debounce depends on, in the same manner as useEffect. The debounce timeout will start when one of the values changes.

Usage

const Demo = {
  setup() {

    const [state, setState] = useState('Typing stopped');
    const [val, setVal] = useState('');
    const [debouncedValue, setDebouncedValue] = useState('');

    const [_, cancel] = useDebounce(
            () => {
              setState('Typing stopped');
              setDebouncedValue(val.value);
            },
            2000,
            [val]
    );

    return () => (
            <div>
              <input
                      type="text"
                      value={val.value}
                      placeholder="Debounced input"
                      onInput={({currentTarget}) => {
                        setState('Waiting for typing to stop...');
                        setVal(currentTarget.value);
                      }}
              />
              <div>{state.value}</div>
              <div>
                Debounced value: {debouncedValue.value}
                <button onClick={cancel}>Cancel debounce</button>
              </div>
            </div>
    );
  }
};

Reference

const [
    isReady: () => boolean | null,
    cancel: () => void,
] = useDebounce(fn: Function, ms: number, deps: DependencyList = []);
  • fn: Function - function that will be called;
  • ms: number - delay in milliseconds;
  • deps: DependencyList - array of values that the debounce depends on, in the same manner as useEffect;
  • isReady: ComputedRef<boolean|null> - the current debounce state:
    • false - pending
    • true - called
    • null - cancelled
  • cancel: ()=>void - cancel the debounce