gpt4 book ai didi

javascript - useCallback 有语义保证吗?

转载 作者:行者123 更新时间:2023-12-03 07:10:01 25 4
gpt4 key购买 nike

React 文档中关于 useMemo 的内容如下

You may rely on useMemo as a performance optimization, not as asemantic guarantee. In the future, React may choose to “forget” somepreviously memoized values and recalculate them on next render, e.g.to free memory for offscreen components. Write your code so that itstill works without useMemo — and then add it to optimize performance.


对于 useCallback有以下行:

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).


“等效”这个词对我来说有点模糊,我不知道这是否也意味着 useCallback不提供语义保证。

最佳答案

useMemo等于 useCallback如果 useMemo 的返回值是一个功能:

// The return value of `useMemo` is calculated every time deps change
useMemo(() => {
return () => { // do some stuff }
}, [deps])

// The function block within `useCallback` is redefined every time deps change
useCallback(() => {
// do some stuff
}, [deps])
我不知道他们为此制作单独的钩子(Hook)的原因,但我猜他们在技术上做同样的事情。
至于有语义保证,我想说他们可能会对 useCallback 做同样的事情。 “释放一些内存”,但函数内存消耗不如实际数据重要。

关于javascript - useCallback 有语义保证吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64685349/

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