# npm

Get unlimited public & private packages + package-based permissions with npm Pro.Get started »

## use-debounce

3.4.0 • Public • Published

# useDebounce react hook

It provides:

Install it with yarn:

yarn add use-debounce


Or with npm:

npm i use-debounce --save


## Demos

The simplest way to start playing around with use-debounce is with this CodeSandbox snippet: https://codesandbox.io/s/kx75xzyrq7

More complex example with searching for matching countries using debounced input: https://codesandbox.io/s/rr40wnropq (thanks to https://twitter.com/ZephDavies)

## Simple values debouncing

This hook compares prev and next value using shallow equal. It means, setting an object {} will trigger debounce timer. If you have to compare objects (https://github.com/xnimorz/use-debounce/issues/27#issuecomment-496828063), you can use useDebounceCallback, that is explained below:

## Debounced callbacks

Besides useDebounce for values you can debounce callbacks, that is the more commonly understood kind of debouncing. Example with Input (and react callbacks): https://codesandbox.io/s/x0jvqrwyq

Example with Scroll (and native event listeners): https://codesandbox.io/s/32yqlyo815

#### Cancel, maxWait and memoization

1. Both useDebounce and useDebouncedCallback works with maxWait option. This params describes the maximum time func is allowed to be delayed before it's invoked.
2. You can cancel debounce cycle, by calling cancel callback

The full example you can see here https://codesandbox.io/s/4wvmp1xlw4

#### callPending method

useDebouncedCallback has callPending method. It allows to call the callback manually if it hasn't fired yet. This method is handy to use when the user takes an action that would cause the component to unmount, but you need to execute the callback.

Both useDebounce and useDebouncedCallback work with the leading option. This param will execute the function once immediately when called. Subsequent calls will be debounced until the timeout expires.

#### Options:

You can provide additional options as a third argument to both useDebounce and useDebounceCallback:

option default Description Example
maxWait - Describes the maximum time func is allowed to be delayed before it's invoked https://github.com/xnimorz/use-debounce#cancel-maxwait-and-memoization
leading - This param will execute the function once immediately when called. Subsequent calls will be debounced until the timeout expires. https://github.com/xnimorz/use-debounce#leading-calls
equalityFn (prev, next) => prev === next Comparator function which shows if timeout should be started

## Keywords

### Install

npm i use-debounce

142,165

3.4.0

MIT

26.9 kB

16

### Repository

github.com/xnimorz/use-debounce