Careeroza
Functional Updates
Update Based on the Previous Value
Example
State updates are batched: calling setCount(count + 1) three times still adds 1, because count is the same value in this render. Pass a function to use the latest value.
import { useState } from 'react';
export default function App() {
const [count, setCount] = useState(0);
const addThreeWrong = () => { setCount(count + 1); setCount(count + 1); setCount(count + 1); };
const addThreeRight = () => { setCount(c => c + 1); setCount(c => c + 1); setCount(c => c + 1); };
return (
<div>
<h2>{count}</h2>
<button onClick={addThreeWrong}>+3 (wrong)</button>
<button onClick={addThreeRight}>+3 (right)</button>
</div>
);
}Result