useThrottleFn

React hook that invokes a function and then delays subsequent function calls until after wait milliseconds have elapsed since the last time the throttled function was invoked.

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

React 钩子,它调用一个函数然后延迟后续函数调用,直到自上次调用了受限制函数后经过等待的毫秒数。

第三个参数是节流所依赖的值,是一个数组,与useEffect的方式相同。 当其中一个值发生变化时,将会开始节流超时。

Usage

  1. import React, { useState } from 'react';
  2. import { useThrottleFn } from 'react-use';
  3. const Demo = () => {
  4. const [status, setStatus] = React.useState('Updating stopped');
  5. const [value, setValue] = React.useState('');
  6. const [throttledValue, setThrottledValue] = React.useState('');
  7. useThrottleFn(
  8. () => {
  9. setStatus('Waiting for input...');
  10. setThrottledValue(value);
  11. },
  12. 2000,
  13. [value]
  14. );
  15. return (
  16. <div>
  17. <input
  18. type="text"
  19. value={value}
  20. placeholder="Throttled input"
  21. onChange={({ currentTarget }) => {
  22. setStatus('Updating stopped');
  23. setValue(currentTarget.value);
  24. }}
  25. />
  26. <div>{status}</div>
  27. <div>Throttled value: {throttledValue}</div>
  28. </div>
  29. );
  30. };

Reference

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