首页 > 解决方案 > 使用空数组作为输入的`useCallback`和没有第二个参数的`useCallback`有什么区别?

问题描述

在我尝试更好地理解 React Hooks 的过程中,我遇到了一些我没想到的行为。我试图创建一个引用数组并通过我将传递给我的 onRef 函数推送到所述数组<div>'s。每次组件重新渲染时,数组都会变得越来越大,大概只是因为它是一个简单的箭头函数并且没有被记忆。

所以然后我添加了useCallback钩子以确保我不会多次获得相同的 ref,但令我惊讶的是,它仍然在每次重新渲染时调用该函数。在添加一个空数组作为第二个参数后,refs 只按预期每个组件触发一次。

下面的代码片段演示了这种行为。

const Example = () => {
  const _refs = React.useRef([]);
  
  // Var to force a re-render.
  const [ forceCount, forceUpdate ] = React.useState(0);
  
  const onRef = (ref) => {
    if (ref && ref !== null) {
      console.log("Adding Ref -> Just an arrow function");
      _refs.current.push(ref);
    }
  }
  
  const onRefCallbackWithoutInputs = React.useCallback((ref) => {
    if (ref && ref !== null) {
      console.log("Adding Ref -> Callback without inputs.");
      _refs.current.push(ref);
    }
  });
  
  const onRefCallbackEmptyArray = React.useCallback((ref) => {
    if (ref && ref !== null) {
      console.log("Adding Ref -> Callback with empty array");
      _refs.current.push(ref);
    }
  }, []);
  
  React.useEffect(() => {
    console.log("Refs size: ", _refs.current.length);
  });
  
  return (
    <div>
      <div ref={onRef}/>
      <div ref={onRefCallbackWithoutInputs}/>
      <div ref={onRefCallbackEmptyArray}/>
      <div onClick={() => forceUpdate(forceCount + 1)} 
        style = {
          {
            width: '100px',
            height: '100px',
            marginTop: '12px',
            backgroundColor: 'orange'
          }
        }>
        {'Click me to update'}
       </div>
    </div>
  );
};

ReactDOM.render(<Example/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>

<div id='root' style='width: 100%; height: 100%'>
</div>

我假设useCallback将有一个空数组作为第二个参数的默认值。那么不给出第二个参数到底是做什么的呢?为什么它的行为不同?

标签: reactjsreact-hooks

解决方案


对于useMemoand useCallback(本质上只是 的一种特殊情况useMemo),如果第二个参数是一个空数组,则该值将被记忆一次并始终返回。

如果省略第二个参数,则永远不会记住该值,并且 theuseCallback和 theuseMemo不会做任何事情。

也许在某些极端情况下,您可以有条件地记住:

useMemo(someValue, shouldMemoize ? [] : null)

但在绝大多数情况下,第二个参数两者都useMemo应该useCallback被认为是强制性的。事实上,Typescript 定义是这样对待它们的。

// Require a second argument, and it must be an array
function useCallback<T extends (...args: any[]) => any>(callback: T, deps: DependencyList): T;

// Second argument can be undefined, but must be explicitly passed as undefined, not omitted.
function useMemo<T>(factory: () => T, deps: DependencyList | undefined): T;

有一个开放的拉取请求正在增强exhaustive-depshooks eslint 规则,因此如果省略第二个参数,它将引发 lint 错误,所以很快这很可能是一个 linter 错误。


推荐阅读