0

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?

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
CerIs
  • 527
  • 3
  • 6
  • 14
  • Did the useeffect trigger when u click button state2? React does trigger a warning when you included `state2` in the useEffect because useEffect presume you need the latest value. – Someone Special Mar 04 '22 at 21:30
  • There's a very good answer in SO which may help you find a way out of your question - https://stackoverflow.com/a/60327893/2822041 – Someone Special Mar 04 '22 at 21:32
  • Does this answer your question? [How to fix missing dependency warning when using useEffect React Hook](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook) – Someone Special Mar 04 '22 at 21:33
  • Not really, these answers about how to ignore dependency array but not why it exists. Ie the official documentation describes "stale data"? – CerIs Mar 05 '22 at 15:12
  • 1
    ? your question is weird. The dependency tells useEffect which state to monitor for changes, and to trigger the useEffect when it change. Do note if the state is not in the dependency array, it just throws a warning, to let u know the state may not be updated. (e.g. in cases where you update both state1 and state2 **at the same time**, useEffect may trigger for state1, but with old value of state2 (because it's not yet updated) – Someone Special Mar 05 '22 at 17:59

0 Answers0