Multiple setState using useState but trigger only once?

 import "./styles.css";
 import React, { useState, useEffect } from "react";

 export default function App() {
  const [count, setCount] = useState(0);
   useEffect(() => {
    console.warn("render");
   });
  function btnClick() {
     setCount(count + 1);
     setCount(count + 1);
  }

return (
<div className="App">
  {count}
  <button onClick={btnClick}>Click Me</button>
</div>
);
}

Button Click only increase by 1, not by 2 and also render once.Any specific behaviour of useState?


This is because both setCount read the same value (in a single render cycle) and the results the same value (Actually, react batch the two updates to a single update and ignores the second update as it is the same as the output of the first update).

To guarantee to get the updated value use the callback updater function with setCount (These updates are also batched to a single update to optimize the rendering but give the correct incremented value - meaning that react does increment twice the value first and set that value to avoid two renders).

function btnClick() {
    setCount((prevCount) => prevCount + 1);
    setCount((prevCount) => prevCount + 1);
}

Code Sandbox