score:1

React will merge all state changes into one update to reduce rendering as rendering costs a lot, setState is not surely updated when you call log. So you can just log("count="+(count+3)) or use useEffect.

useEffect sets a callback when state/prop change; the following snippet shows how to log count every time it changes. You can reference the docs for more information.

const {useState,useEffect} = React;

function App() {
  const [count, setCount] = useState(0);

  useEffect(()=>{
    console.log("effect!count=" + count)
  },[count])

  const onClick = () => {
    setCount((prevCount) => {
      console.log(prevCount + 1);
      return prevCount + 1;
    });

    setCount((prevCount) => {
      console.log(prevCount + 1);
      return prevCount + 1;
    });

    setCount((prevCount) => {
      console.log(prevCount + 1);
      return prevCount + 1;
    });

    console.log("onclick");
  };

  console.log("rendering");

  return <button onClick={onClick}> Increment {count} </button>;
}

ReactDOM.render(<App/>, document.getElementById('app'))
<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="app"></div>


Related Query

More Query from same tag