简体   繁体   English

useCallback 有语义保证吗?

[英]Does useCallback have a semantic guarantee?

The React documentation says the following about useMemo React 文档说明了有关useMemo的以下内容

You may rely on useMemo as a performance optimization, not as a semantic guarantee.您可以依赖 useMemo 作为性能优化,而不是语义保证。 In the future, React may choose to “forget” some previously memoized values and recalculate them on next render, eg to free memory for offscreen components.将来,React 可能会选择“忘记”一些先前记忆的值并在下一次渲染时重新计算它们,例如为屏幕外组件释放内存。 Write your code so that it still works without useMemo — and then add it to optimize performance.编写您的代码,使其在没有 useMemo 的情况下仍然可以工作——然后添加它以优化性能。

For useCallback there is the following line:对于useCallback有以下行:

useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). useCallback(fn, deps) 等价于 useMemo(() => fn, deps)。

The word "equivalent" is a bit fuzzy for me and I don't know if that also means that useCallback does not provide a semantic guarantee. “等效”这个词对我来说有点模糊,我不知道这是否也意味着useCallback不提供语义保证。

useMemo is equal to useCallback if the return value of the useMemo was a function: 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])

I don't know the reason why they made separate hooks for this but I guess they are technically doing the same thing.我不知道他们为此制作了单独的钩子的原因,但我猜他们在技术上正在做同样的事情。

As for having a semantic guarantee, I'd say they might do the same thing with useCallback to "free some memory" but a function memory consumption is less significant than actual data.至于有语义保证,我会说他们可能会用useCallback做同样的事情来“释放一些内存”,但函数内存消耗不如实际数据重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM