lodash 中文文档 lodash 中文文档
英文官网 (opens new window)
GitHub (opens new window)
英文官网 (opens new window)
GitHub (opens new window)
  • 简介
  • 数组
  • 集合
  • 函数
  • 语言
  • 数学
  • 数字
  • 对象
  • Seq
  • 字符串
  • 实用函数
  • Properties

use-lodash-debounce ⏳


Custom react hooks for lodash debounce that provides an easy way to debounce any value, debounced callbacks and types out of the box.

Install


Using yarn or npm:

  1. ``` sh
  2. yarn add use-lodash-debounce
  3. ```

  1. ``` sh
  2. npm i use-lodash-debounce
  3. ```

⚠️react@16.8.0 or greater is required due to the usage of hooks.

Notice that react and lodash.debounce are defined as peer dependencies in order to get a smaller bundle size. This means they should be installed in your project.

Usage


Debounce values throughout re-renders with useDebounce. The debounce will be triggered everytime the value changes (compared using strict equality).

  1. ``` js
  2. import { useDebounce } from 'use-lodash-debounce'

  3. const [value, setValue] = useState()
  4. const debouncedValue = useDebounce(value, 800)
  5. ```

Create debounced callbacks with useDebouncedCallback.

  1. ``` js
  2. import { useDebouncedCallback } from 'use-lodash-debounce'

  3. const [value, setValue] = useState()
  4. const debouncedSetValue = useDebouncedCallback(setValue, 800)
  5. ```

Example


  1. ``` js
  2. import { useDebounce } from 'use-lodash-debounce'

  3. function SearchInput() {
  4.   const [value, setValue] = useState();
  5.   const debouncedValue = useDebounce(value, 1000);

  6.   useEffect(() => {
  7.     // do search stuff
  8.   }, [debouncedValue]);

  9.   return (
  10.     <input
  11.       placeholder="Type to search"
  12.       onChange={e => setValue(e.target.value)}
  13.     />
  14.   );
  15. }
  16. ```

Debounce Options


Lodash debounce supports a set of additional options which can be provided through a third parameter for useDebounce and useDebouncedCallback.

  1. ``` js
  2. const options = { leading: true, maxWait: 1600, trailing: false }
  3. const debouncedSetValue = useDebouncedCallback(setValue, 800, options)
  4. ```

See lodash debounce docs for details.

Cancel / Flush


The callback returned by useDebouncedCallback has a method cancel to cancel delayed function invocations and a flush method to immediately invoke them.

Alternatives


If you're looking for a debounce hook that don't use lodash internally, check out use-debounce.

License


MIT
Last Updated: 2023-05-15 20:35:46