简体   繁体   English

function prop 作为 useCallback 的依赖项

[英]function prop as dependency for useCallback

I am not really sure when we should avoid using useCallback, if there is any harm (memory reallocation).我不太确定我们什么时候应该避免使用 useCallback,如果有任何危害(内存重新分配)。 For example lets say I have a component with two props, {onSave, onClose} and one sate viewName.例如,假设我有一个包含两个道具的组件,{onSave, onClose} 和一个 sate viewName。 is bellow handler function will be optimized with these dependencies?波纹管处理程序 function 是否会使用这些依赖项进行优化?

  const handleSaveView = useCallback(() => {
    onSaveView(viewName, selectedViewList);
    onClose();
  }, [onSaveView, onClose, viewName]);

useCallback saves a function you pass to it and, in the future, returns that function instead of the new one if any of the values in the dependency array change. useCallback保存您传递给它的 function,如果依赖项数组中的任何值发生变化,将来会返回该 function 而不是新值。

This comes at a cost, mostly in the tests of the dependency array and, most of the time, it isn't worth using.这是有代价的,主要是在依赖数组的测试中,而且大多数时候,它不值得使用。 It's a very tempting tool for premature optimization .这是一个非常诱人的过早优化工具。

There are times when that cost is worth paying, such as when the function has an internal state or it is a dependency of another hook (so recreating the function would trigger the other hook to re-run).有时这种成本是值得付出的,例如当 function 具有内部 state 或者它是另一个挂钩的依赖项时(因此重新创建 function 会触发另一个挂钩重新运行)。

Dmitri Pavlutin's "Your Guide to React.useCallback()" covers this in more depth. Dmitri Pavlutin 的“你的 React.useCallback() 指南”对此进行了更深入的介绍。

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

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