Remark: The official documentation is all you need, they explain everything simply and intuitively. This note is for me quickly to find the ideas and references only.
✳️ Before your components are displayed on screen, they must be rendered by React. 👉 Check this doc.
✳️ Click a button which changes the value of a state 3 times at once, why only the first value takes into account? 👉 Check this doc and example.
1// The number only increases once per click!
2export default function Counter() {
3 const [number, setNumber] = useState(0);
4
5 return (
6 <>
7 <h1>{number}</h1>
8 <button onClick={() => {
9 setNumber(number + 1);
10 setNumber(number + 1);
11 setNumber(number + 1);
12 }}>+3</button>
13 </>
14 )
15}
React keeps the state values “fixed” within one render’s event handlers. You don’t need to worry whether the state has changed while the code is running.
React waits until all code in the event handlers has run before processing your state updates. This is why the re-render only happens after all these
setNumber()
calls.❓But what if you wanted to read the latest state before a re-render? → Queueing a Series of State Updates – React
1<button onClick={() => {
2 setNumber(n => n + 1); // n => n+1 called "Updater function"
3 setNumber(n => n + 1);
4 setNumber(n => n + 1);
5}}>+3</button>
It’s common to name the updater function argument by the first letters of the corresponding state variable: