简体   繁体   中英

React useEffect Hook with a single dependency would run N+1 times

useEffect hook with a single dependency would invoke N+1 times, where N is the # of times the dependency mutated. There is an additional invocation that happens during the initial load. Is there a way we can avoid the initial invocation and ONLY run the hook when the dependency actually changed? Here is an example, I am expecting the data to be 1, but if you run this, you would see the value will be 2.

const App = () => {
  const [once, setOnce] = React.useState(null);
  const [data, setData] = React.useState(0);
  let counter = 1;
  React.useEffect(() => {
    setTimeout(() => {
      setOnce(1);
    }, 1000);
  }, []);

  React.useEffect(() => {
    setData(data + 1);
  }, [once]);

  return <p>{data}</p>;
};

Here is a codepen

https://codepen.io/arbinish/pen/qBpXZdq

Add a condition to the second useEffect to stop it from executing at the start such as

React.useEffect(() => {
    if(once){
    setData(data + 1);
    }
  }, [once]);

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