Skip to content

Commit eda939c

Browse files
committed
Section "Queueing a Series of State Updates": await in event handler cause immediate rerender
Signed-off-by: jzz <[email protected]>
1 parent 1e0d713 commit eda939c

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

src/content/learn/queueing-a-series-of-state-updates.md

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,25 @@ setNumber(0 + 1);
5757

5858
But there is one other factor at play here. **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.
5959

60-
This might remind you of a waiter taking an order at the restaurant. A waiter doesn't run to the kitchen at the mention of your first dish! Instead, they let you finish your order, let you make changes to it, and even take orders from other people at the table.
60+
---
61+
62+
### Important Caveat on Using `await` in Event Handlers {/*async-await-state-updates*/}
63+
64+
> **Note:** When using `await` inside an event handler:
65+
>
66+
> - React processes all state updates made before the `await` immediately,
67+
> which triggers a rerender before the handler completes.
68+
>
69+
> - This behavior differs from synchronous event handlers, where React
70+
> waits until the entire handler finishes.
71+
>
72+
> - Any state updates after the `await` will be treated as a separate batch,
73+
> potentially causing multiple renders.
74+
>
75+
> To avoid this behavior, keep all state updates within a single synchronous
76+
> batch, or avoid using `await` inside event handlers when possible.
77+
78+
---
6179

6280
<Illustration src="/images/docs/illustrations/i_react-batching.png" alt="An elegant cursor at a restaurant places and order multiple times with React, playing the part of the waiter. After she calls setState() multiple times, the waiter writes down the last one she requested as her final order." />
6381

0 commit comments

Comments
 (0)