useDebounce

React 钩子,会延迟调用函数,直到上次调用防抖函数以后经过等待毫秒之后。

第三个参数是防抖所依赖的数组值,其方式与 useEffect 中的相同。当其中一个值发生改变,防抖超时将会启动。

用法

  1. import React, { useState } from 'react';
  2. import { useDebounce } from 'react-use';
  3. const Demo = () => {
  4. const [state, setState] = React.useState('Typing stopped');
  5. const [val, setVal] = React.useState('');
  6. useDebounce(
  7. () => {
  8. setState('Typing stopped');
  9. },
  10. 2000,
  11. [val]
  12. );
  13. return (
  14. <div>
  15. <input
  16. type="text"
  17. value={val}
  18. placeholder="Debounced input"
  19. onChange={({ currentTarget }) => {
  20. setState('Waiting for typing to stop...');
  21. setVal(currentTarget.value);
  22. }}
  23. />
  24. <div>{state}</div>
  25. </div>
  26. );
  27. };

参考

  1. useDebouce(fn, ms: number, args: any[]);