简体   繁体   English

如何确定 React.useCallback 的依赖列表?

[英]How to decide the dependency list for React.useCallback?

Consider the following example where the resetCount function can work correctly with an empty dependency list as well.考虑以下示例,其中resetCount function 也可以在空依赖项列表中正常工作。

So, should we include setCount in its dependency?那么,我们应该在它的依赖项中包含setCount吗?
Are there any guidelines to keep in mind?有什么要记住的指导方针吗?
I am interested to know the guidelines for the dependency list in React.useCallback.我很想知道 React.useCallback 中依赖列表的指南。

import React, { useState, useCallback } from 'react';
import { render } from 'react-dom';

import Child from "./Child";
import './style.css';

const Parent = () => {
  const [count, setCount] = useState(0);
  console.log("re-render parent component");

  const resetCount = useCallback(() => {
    setCount(0);
  }, [setCount]); // ([] as well as [setCount] - both work) So should this dependency contain setCount? 

  return (
    <main>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count=>(count+1))}>Increment</button>
      <Child reset={resetCount} />
    </main>
  )
}

render(<Parent />, document.getElementById('root'));

Well, the most definitive advice (and the best starting point for not so advanced React programmers) is: Don't lie to React about dependencies .好吧,最明确的建议(对于不那么高级的 React 程序员来说也是最好的起点)是: 不要在依赖方面对 React 撒谎 With that, it will always work as expected, and you won't get any surprise.有了它,它将始终按预期工作,您不会感到惊讶。

Now you can make exceptions to that rule, if you know that something won't change.现在,如果您知道某些事情不会改变,那么您可以对该规则进行例外处理。 For the set state function returned by the useState hook, this is the case, so you can omit it, yet there is no harm done in leaving it there (cause as it does not change, it won't cause the effect to trigger).对于useState钩子返回的集合state function,是这样的,所以可以省略它,但是放在那里也没有坏处(因为它没有改变,不会导致效果触发) .

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

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