https://react.dev/learn/queueing-a-series-of-state-updates
What is “queue the next render”?
What is the result of this code when you click on the button once?
import { useState } from 'react'; 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> </> ) }
It’s not 3 but 1, why? Because React waits until all code in the event handlers has run before processing your state updates. Each render’s state values are fixed, so the value of number
inside the first render’s event handler is always 0
setNumber(0 + 1); setNumber(0 + 1); setNumber(0 + 1);
How to update the same state multiple times before the next render?
... <button onClick={() => { setNumber(n => n + 1); setNumber(n => n + 1); setNumber(n => n + 1); }}>+3</button> ...
n => n + 1
is called an updater function:
- React queues this function to be processed after all the other code in the event handler has run.
- During the next render, React goes through the queue and gives you the final updated state
React works through these lines of code while executing the event handler:
setNumber(n => n + 1)
:n => n + 1
is a function. React adds it to a queue.setNumber(n => n + 1)
:n => n + 1
is a function. React adds it to a queue.setNumber(n => n + 1)
:n => n + 1
is a function. React adds it to a queue.
queued update | n | returns |
---|---|---|
n => n + 1 | 0 | 0 + 1 = 1 |
n => n + 1 | 1 | 1 + 1 = 2 |
n => n + 1 | 2 | 2 + 1 = 3 |
So the result after one click is 3
What happens if you update state after replacing it?
<button onClick={() => { setNumber(number + 5); setNumber(n => n + 1); }}>
setNumber(number + 5)
:number
is0
, sosetNumber(0 + 5)
. React adds “replace with5
” to its queue.setNumber(n => n + 1)
:n => n + 1
is an updater function. React adds that function to its queue.
queued update | n | returns |
---|---|---|
“replace with 5 ” | 0 (unused) | 5 |
n => n + 1 | 5 | 5 + 1 = 6 |
Result is 6
What happens if you replace state after updating it?
<button onClick={() => { setNumber(number + 5); setNumber(n => n + 1); setNumber(42); }}>
setNumber(number + 5)
:number
is0
, sosetNumber(0 + 5)
. React adds “replace with5
” to its queue.setNumber(n => n + 1)
:n => n + 1
is an updater function. React adds that function to its queue.setNumber(42)
: React adds “replace with42
” to its queue.
queued update | n | returns |
---|---|---|
“replace with 5 ” | 0 (unused) | 5 |
n => n + 1 | 5 | 5 + 1 = 6 |
“replace with 42 ” | 6 (unused) | 42 |
Result is 42
Leave a Reply