Search code examples
reactjsreact-hooksuse-effect

React conditional action - useEffect vs an if statement


Relatively new to React and ran into something that I wasn't sure the answer about. If you have a conditional action, is there a difference between useEffect and just having the if statement?

function Items() {
    [setItemAdded, itemAdded] = useState(false);
    
    if (itemAdded) {
      saveData();
      itemAdded = false;
    }

}

vs

     useEffect(() => {
         if (itemAdded) {
             saveData();
             itemAdded = false;
         }, [itemAdded]);
          

From my understanding, when the state updates itemAdded, it will re-render the component which would call the conditional statement and execute the code.

In the 2nd case, since itemAdded is a dependency it will get called whenever itemAdded is changed. To me, both scenarios seem to have the same effect. Is there a difference between the two?


Solution

  • Yes, absolutely, and you will see the difference by adding another state and updating it.

    if statement is getting executed on every render but useEffect is only getting executed according to its dependency (item in the array).

    I recommend using useEffect instead of if statement