Friday, 15 October 2021

State update being overridden by another (previous) state update?

I know this seems as unusual example, but still I can't seem to explain precisely why do I never see valueB printed on console after I click the div?

Note that since I am calling the two set state calls in a setTimeout, they are not batched.

function App() {
  let [a, setA] = React.useState();
  let [b, setB] = React.useState();

  React.useEffect(() => {
    console.log('Entering useEffect', a, b);

    return () => {
      console.log('Entering cleanup', a, b);

      setA(null);
      setB(null);
    };
  }, [a, b]);

  console.log('Render', a, b);

  return (
    <div
      onClick={() => {
        setTimeout(() => {
          setA('valueA');
          setB('valueB');
        }, 100);
      }}
    >
      <h1>Test App</h1>
    </div>
  );
}

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


from State update being overridden by another (previous) state update?

No comments:

Post a Comment