简体   繁体   中英

run useEffect Hook only after condition is met

My component uses the useEffect hook to watch for updates of a valve.

I have set a condition to prevent useEffect firing after mounting.

When the button is clicked, the value is updated from the initial state. Why does useEffect gets fired every time the button is clicked? The value is always the same so there's no update.

import React, { useState, useEffect } from "react";

function doSomething() {
  return [
    { id: 1, prop1: "foo", prop2: "bar" },
  ];
}
export default function Choose() {
  const [tableData, setTableData] = useState([{}])

  // runs after every render
  
  useEffect(()=> {
    if (Object.keys(tableData[0]).length > 0) {
      console.log("something changed")
    }
  
  }, [tableData])  

  return (
    <div>
      <button type="button" onClick={(e)=> setTableData(doSomething())}>display</button>
       
    </div>
  );
}

The doSomething function generates a new object, each time you click the button. Declare the array outside of the function, and return it inside it:

const arr = [
  { id: 1, prop1: "foo", prop2: "bar" },
]

function doSomething() {
  return arr;
}

Example:

 const { useState, useEffect } = React; const arr = [ { id: 1, prop1: "foo", prop2: "bar" }, ]; function doSomething() { return arr; } function Choose() { const [tableData, setTableData] = useState([{}]) useEffect(()=> { if (Object.keys(tableData[0]).length > 0) { console.log("something changed " + Math.random()); } }, [tableData]) return ( <div> <button type="button" onClick={(e)=> setTableData(doSomething())}>display</button> </div> ); } ReactDOM.render( <Choose />, root );
 <script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="root"></div>

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