简体   繁体   中英

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.

So, should we include setCount in its dependency?
Are there any guidelines to keep in mind?
I am interested to know the guidelines for the dependency list in 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 . 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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