如何使用油门或反作用钩退出?

我试图在函数组件中使用来自 lodashthrottle方法,例如:

const App = () => {
const [value, setValue] = useState(0)
useEffect(throttle(() => console.log(value), 1000), [value])
return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}

因为 useEffect中的方法在每次渲染时都会重新声明,所以节流效果不起作用。

有人有简单的解决办法吗?

172735 次浏览

经过一段时间后,我确信使用 setTimeout/clearTimeout(并将其移动到单独的自定义钩子中)自己处理事情要比使用函数式助手容易得多。稍后的处理会在我们将其应用到 useCallback之后产生额外的挑战,这些挑战可以由于依赖关系的改变而重新创建,但是我们不想重置延迟运行。

原答案如下

你可能(也可能需要) useRef来存储渲染之间的值,就像它是 建议用于计时器一样

Something like that

const App = () => {
const [value, setValue] = useState(0)
const throttled = useRef(throttle((newValue) => console.log(newValue), 1000))


useEffect(() => throttled.current(value), [value])


return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}

至于 useCallback:

它也可以作为

const throttled = useCallback(throttle(newValue => console.log(newValue), 1000), []);

但是,如果我们尝试在 value改变后重新创建回调:

const throttled = useCallback(throttle(() => console.log(value), 1000), [value]);

我们可能会发现它并没有延迟执行: 一旦 value被改变,回调就会立即重新创建并执行。

所以我看到 useCallback在延迟运行的情况下并没有提供显著的优势。这取决于你。

一开始是的

  const throttled = useRef(throttle(() => console.log(value), 1000))


useEffect(throttled.current, [value])

但这样 throttled.current通过闭包绑定到初始 value(为0)。所以即使在下一次渲染中也没有改变。

因此,在将函数推入 useRef时要小心,因为它具有闭包特性。

我为这个用例编写了两个简单的钩子(使用-节流-效果使用-消除-效果) ,也许对于其他寻找简单解决方案的人会有用。

import React, { useState } from 'react';
import useThrottledEffect  from 'use-throttled-effect';


export default function Input() {
const [count, setCount] = useState(0);


useEffect(()=>{
const interval = setInterval(() => setCount(count=>count+1) ,100);
return ()=>clearInterval(interval);
},[])


useThrottledEffect(()=>{
console.log(count);
}, 1000 ,[count]);


return (
{count}
);
}

如果你使用它在处理程序,我相当肯定这是这样做的方式。

function useThrottleScroll() {
const savedHandler = useRef();


function handleEvent() {}


useEffect(() => {
savedHandleEvent.current = handleEvent;
}, []);


const throttleOnScroll = useRef(throttle((event) => savedHandleEvent.current(event), 100)).current;


function handleEventPersistence(event) {
return throttleOnScroll(event);
}


return {
onScroll: handleEventPersistence,
};
}

我使用这样的东西,它的工作原理很好:

let debouncer = debounce(
f => f(),
1000,
{ leading: true }, // debounce one on leading and one on trailing
);


function App(){
let [state, setState] = useState();


useEffect(() => debouncer(()=>{
// you can use state here for new state value
}),[state])


return <div />
}

它可以是一个很小的定制钩子,像这样:

useDebounce.js

import React, { useState, useEffect } from 'react';


export default (value, timeout) => {
const [state, setState] = useState(value);


useEffect(() => {
const handler = setTimeout(() => setState(value), timeout);


return () => clearTimeout(handler);
}, [value, timeout]);


return state;
}

Usage example:

import React, { useEffect } from 'react';


import useDebounce from '/path/to/useDebounce';


const App = (props) => {
const [state, setState] = useState({title: ''});
const debouncedTitle = useDebounce(state.title, 1000);


useEffect(() => {
// do whatever you want with state.title/debouncedTitle
}, [debouncedTitle]);


return (
// ...
);
}
// ...

注意: 你可能知道,useEffect总是在初始渲染时运行,因此如果你使用我的答案,你可能会看到组件的渲染运行两次,不要担心,你只需要编写另一个自定义钩子。查看 我的另一个答案了解更多信息。

In my case I also needed to pass the event. Went with this:

const MyComponent = () => {
const handleScroll = useMemo(() => {
const throttled = throttle(e => console.log(e.target.scrollLeft), 300);
return e => {
e.persist();
return throttled(e);
};
}, []);
return <div onScroll={handleScroll}>Content</div>;
};

我已经创建了自己的自定义钩子 useDebouncedEffect,它将等待执行 useEffect,直到延迟期间状态没有更新为止。

在本例中,当您停止单击按钮1秒钟后,您的效果将记录到控制台。

沙盒示例 Https://codesandbox.io/s/react-use-debounced-effect-6jppw

App.jsx

import { useState } from "react";
import { useDebouncedEffect } from "./useDebouncedEffect";


const App = () => {
const [value, setValue] = useState(0)


useDebouncedEffect(() => console.log(value), [value], 1000);


return (
<button onClick={() => setValue(value + 1)}>{value}</button>
)
}


export default App;

useDebouncedEffect.js

import { useEffect } from "react";


export const useDebouncedEffect = (effect, deps, delay) => {
useEffect(() => {
const handler = setTimeout(() => effect(), delay);


return () => clearTimeout(handler);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [...(deps || []), delay]);
}

除非您希望看到警告,否则需要禁用穷尽 deps 的注释,因为 lint 总是抱怨没有作为依赖项的效果。添加效果作为依赖项将在每次渲染中触发 useEffect。相反,您可以将检查添加到 useDebouncedEffect,以确保它正在传递所有的依赖项。(见下文)

useDebouncedEffect添加穷举依赖性检查

如果希望让 eslint 检查 useDebouncedEffect是否有详尽的依赖项,可以将其添加到 package.json中的 eslint 配置中

  "eslintConfig": {
"extends": [
"react-app"
],
"rules": {
"react-hooks/exhaustive-deps": ["warn", {
"additionalHooks": "useDebouncedEffect"
}]
}
},

https://github.com/facebook/react/tree/master/packages/eslint-plugin-react-hooks#advanced-configuration

useThrottleuseDebounce

如何同时使用

const App = () => {
const [value, setValue] = useState(0);
// called at most once per second (same API with useDebounce)
const throttledCb = useThrottle(() => console.log(value), 1000);
// usage with useEffect: invoke throttledCb on value change
useEffect(throttledCb, [value]);
// usage as event handler
<button onClick={throttledCb}>log value</button>
// ... other render code
};

useThrottle(Lodash)

import _ from "lodash"


function useThrottle(cb, delay) {
const options = { leading: true, trailing: false }; // add custom lodash options
const cbRef = useRef(cb);
// use mutable ref to make useCallback/throttle not depend on `cb` dep
useEffect(() => { cbRef.current = cb; });
return useCallback(
_.throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
}

const App = () => {
const [value, setValue] = useState(0);
const invokeDebounced = useThrottle(
() => console.log("changed throttled value:", value),
1000
);
useEffect(invokeDebounced, [value]);
return (
<div>
<button onClick={() => setValue(value + 1)}>{value}</button>
<p>value will be logged at most once per second.</p>
</div>
);
};


function useThrottle(cb, delay) {
const options = { leading: true, trailing: false }; // pass custom lodash options
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
_.throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>

useDebounce(Lodash)

import _ from "lodash"


function useDebounce(cb, delay) {
// ...
const inputsRef = useRef({cb, delay}); // mutable ref like with useThrottle
useEffect(() => { inputsRef.current = { cb, delay }; }); //also track cur. delay
return useCallback(
_.debounce((...args) => {
// Debounce is an async callback. Cancel it, if in the meanwhile
// (1) component has been unmounted (see isMounted in snippet)
// (2) delay has changed
if (inputsRef.current.delay === delay && isMounted())
inputsRef.current.cb(...args);
}, delay, options
),
[delay, _.debounce]
);
}

const App = () => {
const [value, setValue] = useState(0);
const invokeDebounced = useDebounce(
() => console.log("debounced", value),
1000
);
useEffect(invokeDebounced, [value]);
return (
<div>
<button onClick={() => setValue(value + 1)}>{value}</button>
<p> Logging is delayed until after 1 sec. has elapsed since the last invocation.</p>
</div>
);
};


function useDebounce(cb, delay) {
const options = {
leading: false,
trailing: true
};
const inputsRef = useRef(cb);
const isMounted = useIsMounted();
useEffect(() => {
inputsRef.current = { cb, delay };
});


return useCallback(
_.debounce(
(...args) => {
// Don't execute callback, if (1) component in the meanwhile
// has been unmounted or (2) delay has changed
if (inputsRef.current.delay === delay && isMounted())
inputsRef.current.cb(...args);
},
delay,
options
),
[delay, _.debounce]
);
}


function useIsMounted() {
const isMountedRef = useRef(true);
useEffect(() => {
return () => {
isMountedRef.current = false;
};
}, []);
return () => isMountedRef.current;
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>


Customizations

1. 你可以用自己的 throttledebounce代码替换 Lodash,比如:

const debounceImpl = (cb, delay) => {
let isDebounced = null;
return (...args) => {
clearTimeout(isDebounced);
isDebounced = setTimeout(() => cb(...args), delay);
};
};


const throttleImpl = (cb, delay) => {
let isThrottled = false;
return (...args) => {
if (isThrottled) return;
isThrottled = true;
cb(...args);
setTimeout(() => {
isThrottled = false;
}, delay);
};
};


const App = () => {
const [value, setValue] = useState(0);
const invokeThrottled = useThrottle(
() => console.log("throttled", value),
1000
);
const invokeDebounced = useDebounce(
() => console.log("debounced", value),
1000
);
useEffect(invokeThrottled, [value]);
useEffect(invokeDebounced, [value]);
return <button onClick={() => setValue(value + 1)}>{value}</button>;
};


function useThrottle(cb, delay) {
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
throttleImpl((...args) => cbRef.current(...args), delay),
[delay]
);
}


function useDebounce(cb, delay) {
const cbRef = useRef(cb);
useEffect(() => {
cbRef.current = cb;
});
return useCallback(
debounceImpl((...args) => cbRef.current(...args), delay),
[delay]
);
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>

2. 如果总是与 useEffect一起使用,useThrottle可以缩短(useDebounce也是如此) :

const App = () => {
// useEffect now is contained inside useThrottle
useThrottle(() => console.log(value), 1000, [value]);
// ...
};

const App = () => {
const [value, setValue] = useState(0);
useThrottle(() => console.log(value), 1000, [value]);
return (
<div>
<button onClick={() => setValue(value + 1)}>{value}</button>
<p>value will be logged at most once per second.</p>
</div>
);
};


function useThrottle(cb, delay, additionalDeps) {
const options = { leading: true, trailing: false }; // pass custom lodash options
const cbRef = useRef(cb);
const throttledCb = useCallback(
_.throttle((...args) => cbRef.current(...args), delay, options),
[delay]
);
useEffect(() => {
cbRef.current = cb;
});
// set additionalDeps to execute effect, when other values change (not only on delay change)
useEffect(throttledCb, [throttledCb, ...additionalDeps]);
}


ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js" integrity="sha256-32Gmw5rBDXyMjg/73FgpukoTZdMrxuYW7tj8adbN8z4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js" integrity="sha256-bjQ42ac3EN0GqK40pC9gGi/YixvKyZ24qMP/9HiGW7w=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js" integrity="sha256-VeNaFBVDhoX3H+gJ37DpT/nTuZTdjYro9yBruHjVmoQ=" crossorigin="anonymous"></script>
<script>var { useReducer, useEffect, useState, useRef, useCallback } = React</script>
<div id="root"></div>

在这里使用 loash 的 deounce 函数就是我要做的:

import debounce from 'lodash/debounce'


// The function that we want to debounce, for example the function that makes the API calls
const getUsers = (event) => {
// ...
}




// The magic!
const debouncedGetUsers = useCallback(debounce(getUsers, 500), [])

在你的 JSX 中:

<input value={value} onChange={debouncedGetUsers} />

我来得有点晚了,不过这里有一个去除 setState()的方法

/**
* Like React.setState, but debounces the setter.
*
* @param {*} initialValue - The initial value for setState().
* @param {int} delay - The debounce delay, in milliseconds.
*/
export const useDebouncedState = (initialValue, delay) => {
const [val, setVal] = React.useState(initialValue);
const timeout = React.useRef();
const debouncedSetVal = newVal => {
timeout.current && clearTimeout(timeout.current);
timeout.current = setTimeout(() => setVal(newVal), delay);
};


React.useEffect(() => () => clearTimeout(timeout.current), []);
return [val, debouncedSetVal];
};

这是我的 useDebounce:

export function useDebounce(callback, timeout, deps) {
const timeoutId = useRef();


useEffect(() => {
clearTimeout(timeoutId.current);
timeoutId.current = setTimeout(callback, timeout);


return () => clearTimeout(timeoutId.current);
}, deps);
}

你可以这样使用它:

const TIMEOUT = 500; // wait 500 milliseconds;


export function AppContainer(props) {
const { dataId } = props;
const [data, setData] = useState(null);
//
useDebounce(
async () => {
data = await loadDataFromAPI(dataId);
setData(data);
},
TIMEOUT,
[dataId]
);
//
}

我编写了一个简单的 useDebounce挂钩,它考虑到了清理工作,就像 useEffect工作一样。

import { useState, useEffect, useRef, useCallback } from "react";


export function useDebounceState<T>(initValue: T, delay: number) {
const [value, setValue] = useState<T>(initValue);
const timerRef = useRef(null);
// reset timer when delay changes
useEffect(
function () {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
},
[delay]
);
const debounceSetValue = useCallback(
function (val) {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
timerRef.current = setTimeout(function () {
setValue(val);
}, delay);
},
[delay]
);
return [value, debounceSetValue];
}


interface DebounceOptions {
imediate?: boolean;
initArgs?: any[];
}


const INIT_VALUE = -1;
export function useDebounce(fn, delay: number, options: DebounceOptions = {}) {
const [num, setNum] = useDebounceState(INIT_VALUE, delay);
// save actual arguments when fn called
const callArgRef = useRef(options.initArgs || []);
// save real callback function
const fnRef = useRef(fn);
// wrapped function
const trigger = useCallback(function () {
callArgRef.current = [].slice.call(arguments);
setNum((prev) => {
return prev + 1;
});
}, []);
// update real callback
useEffect(function () {
fnRef.current = fn;
});
useEffect(
function () {
if (num === INIT_VALUE && !options.imediate) {
// prevent init call
return;
}
return fnRef.current.apply(null, callArgRef.current);
},
[num, options.imediate]
);
return trigger;
}

要点在这里: https://gist.github.com/sophister/9cc74bb7f0509bdd6e763edbbd21ba64

这是现场演示: https://codesandbox.io/s/react-hook-debounce-demo-mgr89?file=/src/App.js

用途:

const debounceChange = useDebounce(function (e) {
console.log("debounced text change: " + e.target.value);
}, 500);
// can't use debounceChange directly, since react using event pooling
function deboucnedCallback(e) {
e.persist();
debounceChange(e);
}


// later the jsx
<input onChange={deboucnedCallback} />

我想加入这个派对,使用 useState进行我的节流和去噪输入:

// import { useState, useRef } from 'react' // nomral import
const { useState, useRef } = React // inline import


// Throttle


const ThrottledInput = ({ onChange, delay = 500 }) => {
const t = useRef()
  

const handleChange = ({ target }) => {
if (!t.current) {
t.current = setTimeout(() => {
onChange(target.value)
clearTimeout(t.current)
t.current = null
}, delay)
}
}
  

return (
<input
placeholder="throttle"
onChange={handleChange}
/>
)
}




// Debounce


const DebouncedInput = ({ onChange, delay = 500 }) => {
const t = useRef()
  

const handleChange = ({ target }) => {
clearTimeout(t.current)
t.current = setTimeout(() => onChange(target.value), delay)
}
  

return (
<input
placeholder="debounce"
onChange={handleChange}
/>
)
}


// ----


ReactDOM.render(<div>
<ThrottledInput onChange={console.log} />
<DebouncedInput onChange={console.log} />
</div>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>

这是一个真正的油门钩。您可以在屏幕或组件中使用所有希望节流的函数,它们将共享相同的节流。或者您可以多次调用 useThrottle(),并为各个函数设置不同的节流。

Use like this:

import useThrottle from '../hooks/useThrottle';


const [navigateToSignIn, navigateToCreateAccount] = useThrottle([
() => { navigation.navigate(NavigationRouteNames.SignIn) },
() => { navigation.navigate(NavigationRouteNames.CreateAccount) }
])

还有钩子本身:

import { useCallback, useState } from "react";


// Throttles all callbacks on a component within the same throttle.
// All callbacks passed in will share the same throttle.


const THROTTLE_DURATION = 500;


export default (callbacks: Array<() => any>) => {
const [isWaiting, setIsWaiting] = useState(false);


const throttledCallbacks = callbacks.map((callback) => {
return useCallback(() => {
if (!isWaiting) {
callback()
setIsWaiting(true)
setTimeout(() => {
setIsWaiting(false)
}, THROTTLE_DURATION);
}
}, [isWaiting]);
})


return throttledCallbacks;
}

这里有一个简单的钩子来清除你的电话。

要使用下面的代码,所有您需要做的就是这样声明它

const { debounceRequest } = useDebounce(someFn);

然后就这么说

debounceRequest();

实现如下所示

import React from "react";


const useDebounce = (callbackFn: () => any, timeout: number = 500) => {
const [sends, setSends] = React.useState(0);


const stabilizedCallbackFn = React.useCallback(callbackFn, [callbackFn]);


const debounceRequest = () => {
setSends(sends + 1);
};


// 1st send, 2nd send, 3rd send, 4th send ...
// when the 2nd send comes, then 1st set timeout is cancelled via clearInterval
// when the 3rd send comes, then 2nd set timeout is cancelled via clearInterval
// process continues till timeout has passed, then stabilizedCallbackFn gets called
// return () => clearInterval(id) is critical operation since _this_ is what cancels
//  the previous send.
// *🎗 return () => clearInterval(id) is called for the previous send when a new send
// is sent. Essentially, within the timeout all but the last send gets called.


React.useEffect(() => {
if (sends > 0) {
const id = window.setTimeout(() => {
stabilizedCallbackFn();
setSends(0);
}, timeout);
return () => {
return window.clearInterval(id);
};
}
}, [stabilizedCallbackFn, sends, timeout]);


return {
debounceRequest,
};
};


export default useDebounce;
const useDebounce = (func: any) => {
const debounceFunc = useRef(null);


useEffect(() => {
if (func) {
// @ts-ignore
debounceFunc.current = debounce(func, 1000);
}
}, []);


const debFunc = () => {
if (debounceFunc.current) {
return debounceFunc.current;
}
return func;
};
return debFunc();
};

借助 useCallback 钩子弹出。

import React, { useState, useCallback } from 'react';
import debounce from 'lodash.debounce';


function App() {
const [value, setValue] = useState('');
const [dbValue, saveToDb] = useState(''); // would be an API call normally


// highlight-starts
const debouncedSave = useCallback(
debounce(nextValue => saveToDb(nextValue), 1000),
[], // will be created only once initially
);
// highlight-ends


const handleChange = event => {
const { value: nextValue } = event.target;
setValue(nextValue);
// Even though handleChange is created on each render and executed
// it references the same debouncedSave that was created initially
debouncedSave(nextValue);
};


return <div></div>;
}

And one more implementation. Custom hook:

function useThrottle (func, delay) {
const [timeout, saveTimeout] = useState(null);
    

const throttledFunc = function () {
if (timeout) {
clearTimeout(timeout);
}


const newTimeout = setTimeout(() => {
func(...arguments);
if (newTimeout === timeout) {
saveTimeout(null);
}
}, delay);


saveTimeout(newTimeout);
}


return throttledFunc;
}

and usage:

const throttledFunc = useThrottle(someFunc, 200);

希望能帮到别人。

我做了一个简单的钩子来创建油门实例。

It takes a slightly different approach, passing in the function to call each time rather that trying to wrap it and manage mutations. A lot of the other solutions don't account for the function to call potentially changing. Pattern works well with throttle or debounce.

// useThrottle.js
import React, { useCallback } from 'react';
import throttle from 'lodash/throttle';


export function useThrottle(timeout = 300, opts = {}) {
return useCallback(throttle((fn, ...args) => {
fn(...args);
}, timeout, opts), [timeout]);
}

使用方法:

...
const throttleX = useThrottle(100);


const updateX = useCallback((event) => {
// do something!
}, [someMutableValue])


return (
<div onPointerMove={(event) => throttleX(updateX, event)}></div>
)
...

I believe this hook works properly by giving the option to fire immediately.

import { useState, useRef, useEffect } from 'react';


const useDebounce = <T>(
value: T,
timeout: number,
immediate: boolean = true
): T => {
const [state, setState] = useState<T>(value);
const handler = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);


useEffect(() => {
if (handler.current) {
clearTimeout(handler.current);
handler.current = undefined;
} else if (immediate) {
setState(value);
}


handler.current = setTimeout(() => {
setState(value);
handler.current = undefined;
}, timeout);
}, [value, timeout, immediate]);


return state;
};


export default useDebounce;

当我试图解决一个陈旧状态的问题时,我想出了以下模式:

We can store the debounced function in a ref and update it each time the component rerenders in useEffect like this:

  // some state
const [counter, setCounter] = useState(0);


// store a ref to the function we will debounce
const increment = useRef(null);


// update the ref every time the component rerenders
useEffect(() => {
increment.current = () => {
setCounter(counter + 1);
};
});


// debounce callback, which we can call (i.e. in button.onClick)
const debouncedIncrement = useCallback(
debounce(() => {
if (increment) {
increment.current();
}
}, 1500),
[]
);


// cancel active debounces on component unmount
useEffect(() => {
return () => {
debouncedIncrement.cancel();
};
}, []);


代码沙盒: https://codesandbox.io/s/debounced-function-ref-pdrfu?file=/src/index.js

我希望这能让某人少挣扎几个小时

您可以使用 useMemo钩子来优化您的节流事件处理程序

Example code below:

const App = () => {
const [value, setValue] = useState(0);


// ORIGINAL EVENT HANDLER
function eventHandler(event) {
setValue(value + 1);
}


// THROTTLED EVENT HANDLER
const throttledEventHandler = useMemo(() => throttle(eventHandler, 1000), [value]);
  

return (
<button onClick={throttledEventHandler}>Throttled Button with value: {value}</button>
)
}

My solution is similar to this https://stackoverflow.com/a/68357888/6083689 (features useMemo), however I'm passing the argument directly to debounced function in useEffect, instead of treating it as dependency. It solves the problem of re-creating the hooks by separating the arguments (which supposed to be re-created) and debounced function (which shouldn't be re-created).

const MyComponent: FC<Props> = ({ handler, title }) => {
const payload = useMemo<Payload>(() => ({ title }), [title])
const debouncedHandler = useMemo(() => debounce(handler, 1000), [handler])


useEffect(() => debouncedHandler(payload), [payload, debouncedHandler])
}
function myThrottle(callback, delay) {
var previousTime = 0;
return function (...args) {
let currentTime = Date.now();
let gap = currentTime - previousTime;
if (gap > 0) {
previousTime = currentTime + delay;
callback.call(this, ...args);
}
return;
};
}

在函数组件中使用下面的代码。

const memoizedCallback = useMemo(() => myThrottle(callback, 3000), []);

使用 备忘录,回拨作为 复试