You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When the setter is called inside an Action, `useOptimistic` will trigger a re-render to show that value while the Action is in progress. Otherwise, the `value` passed to `useOptimistic` is returned.
99
+
When the setter is called inside an Action, `useOptimistic` will trigger a re-render to show that state while the Action is in progress. Otherwise, the `value` passed to `useOptimistic` is returned.
99
100
100
101
This state is called the "optimistic" because it is used to immediately present the user with the result of performing an Action, even though the Action actually takes time to complete.
101
102
102
-
When the Action completes, `useOptimistic` returns the current `value` you passed in.
103
-
104
103
**How the update flows**
105
104
106
-
1. **Immediate optimistic update**: When `setOptimistic('b')` is called, `optimistic` immediately becomes `'b'` and React renders with this state.
105
+
1. **Update immediately**: When `setOptimistic('b')` is called, React immediately renders with `'b'`.
106
+
107
+
2. **(Optional) await in Action**: If you await in the Action, React continues showing `'b'`.
107
108
108
-
2. **Transition scheduled**: `setValue('b')` schedules an update to the real state, but this update won't commit until the Action completes.
109
+
3. **Transition scheduled**: `setValue(newValue)` schedules an update to the real state.
109
110
110
-
3. **Optimistic state persists during async work**: If the Transition suspends or uses `await`, the optimistic `'b'` continues showing while React waits.
111
+
4. **(Optional) wait for Suspense**: If `newValue` suspends, React continues showing `'b'`.
111
112
112
-
4. **Single render commit**: When all async work finishes, the new state (`'b'`) and optimistic state (`'b'`) commit together in a single render.
113
+
5. **Single render commit**: Finally, the `newValue` is commits for `value` and `optimistic`.
113
114
114
115
There's no extra render to "clear" the optimistic state. The optimistic and real state converge in the same render when the Transition completes.
115
116
117
+
<Note>
118
+
119
+
#### Optimistic state is temporary {/*optimistic-state-is-temporary*/}
120
+
121
+
Optimistic state is only renders while an Action is in progress, otherwise `value` is rendered.
122
+
123
+
If `saveChanges` returned `'c'`, then both `value` and `optimistic` will be `'c'`, not `'b'`.
124
+
125
+
</Note>
126
+
116
127
**How the final state is determined**
117
128
118
129
The `value` argument to `useOptimistic` determines what displays after the Action finishes. How this works depends on the pattern you use:
0 commit comments