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.
Image taken from the 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.
// The number only increases once per click!
export default function Counter() {
const [number, setNumber] = useState(0);
return (
<>
<h1>{number}</h1>
<button onClick={() => {
setNumber(number + 1);
setNumber(number + 1);
setNumber(number + 1);
}}>+3</button>
</>
)
}
<aside> ☝ 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.
</aside>
<aside>
☝ 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.
</aside>
❓But what if you wanted to read the latest state before a re-render? → Queueing a Series of State Updates – React
<button onClick={() => {
setNumber(n => n + 1); // n => n+1 called "Updater function"
setNumber(n => n + 1);
setNumber(n => n + 1);
}}>+3</button>
<aside> ☝ It’s common to name the updater function argument by the first letters of the corresponding state variable:
</aside>