'I can get latest state in useEffect so why include in dependency array?

I understand that useEffect will run again if an item in its dependency array has changed but its true that I can get the latest values in state without this? Ie see below:

const { useState, useEffect } = React;

function App() {
  const [state1, setState1] = useState(0);
  const [state2, setState2] = useState(0);
  const [state3, setState3] = useState(0);

  useEffect(() => {
    
    console.log("State1", state1);
    console.log("State2", state2);
    console.log("State3", state3);

  }, [state1]);

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <button onClick={() => setState1((x) => x + 1)}>State1</button>
      <button onClick={() => setState2((x) => x + 1)}>State2</button>
      <button onClick={() => setState3((x) => x + 1)}>State3</button>

    </div>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>

So if I click "State 2 button" 5 times then click "State 1 button" which triggers the useEffect it will still get the latest values for state 2? In short if I dont want a state action to trigger the useEffect why do I have to include it?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source