gpt4 book ai didi

debouncing in react using useRef and useMemo(使用useRef和useMemo在react中消除抖动)

转载 作者:bug小助手 更新时间:2023-10-28 11:46:07 42 4
gpt4 key购买 nike



I am trying to implement debounce in react js , and I have written the following code .

我正在尝试在Reaction js中实现去反跳,并且我已经编写了以下代码。


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

function debounce(fn) {
let timer = null;
return function () {
clearTimeout(timer);
timer = setTimeout(fn, 1000)
}
}

export default function () {

const [value, setValue] = useState("");
const myRef = useRef(handlChangeUtil);

//it logs the value of state
//closure : this is closed on 'value'
function handlChangeUtil() {
console.log(value);
}


//attaching the newer version of handChangeUtil function to myRef
//since the mounted function won't have the newer value;
useEffect(() => {
myRef.current = handlChangeUtil;
}, [value]);

//it should return the debounced function during the mounting only

const handlChangeUtilDebounce = useMemo(() => {

//this code works
// const func = () => {
// myRef.current();
// }

// return debounce(func)

//this code doesnt't work
return debounce(myRef.current);
} , []);


function handleChange(e) {
setValue(e.target.value);
handlChangeUtilDebounce();
}

return (
<div>
<input value={value} onChange={handleChange} />
</div>
)

}

In the useMemo if i return debounce(myRef.current) it will always log the inital value of state i.e "" . However if i call myRef.current() inside the function , and pass that function in debounce (refer the code) , it's executing the updated value of state. What is the difference in both the codes?

在useMemo中,如果我返回DEBAKE(myRef.Current),它将始终记录状态的初始值,即“”。但是,如果我在该函数中调用myRef.Current(),并将该函数传递到Dieb中(请参阅代码),它将执行状态的更新值。这两个代码有什么不同?


更多回答
优秀答案推荐

useMemo caches your last result of the function and returns it again and again as long as the value of the dependency array is changed.

UseMemo缓存函数的最后结果,只要依赖项数组的值发生更改,就会一次又一次地返回它。


In this scenario, you didn't add any dependency key to it, actually, if you pass myRef.current as a dependency key to it, it doesn't work again because ref object changes don't affect react rerender

在这个场景中,您没有向它添加任何依赖键,实际上,如果您将myRef.Current作为依赖键传递给它,它不会再次工作,因为Ref对象的更改不会影响Reaction重新呈现


For more info please read these pages:

https://react.dev/reference/react/useMemo

https://react.dev/reference/react/useRef

欲了解更多信息,请阅读以下页面:https://react.dev/reference/react/useMemo https://react.dev/reference/react/useRef


更多回答

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com