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
Copy file name to clipboardExpand all lines: src/content/reference/react/useOptimistic.md
+4-19Lines changed: 4 additions & 19 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -388,13 +388,7 @@ See [Updating state based on the current state](#updating-state-based-on-current
388
388
389
389
### Updating state based on the current state {/*updating-state-based-on-current-state*/}
390
390
391
-
The previous example toggles `isLiked` by reading from the current optimistic state:
392
-
393
-
```js
394
-
setOptimisticIsLiked(!optimisticIsLiked);
395
-
```
396
-
397
-
This works fine for simple cases, but can cause issues if the base state changes while your action is pending. For example, if another user's action changes the `isLiked` state on the server while you're waiting, your toggle could apply to the wrong value.
391
+
The [previous example](#updating-props-or-state-optimistically) reads from the current optimistic state, which can cause issues if the base state changes while the action is pending.
398
392
399
393
To calculate the optimistic state relative to the current state, pass an updater function:
**Use updaters** for simple calculations where the setter call naturally describes the update. This is similar to using `setState(prev=>...)` with `useState`.
484
471
485
472
**Use reducers** when you need to pass data to the update (like which item to add) or when handling multiple types of updates with a single hook.
@@ -1019,11 +1006,7 @@ function MyComponent({ items }) {
1019
1006
1020
1007
### My optimistic updates show stale values {/*my-optimistic-updates-show-stale-values*/}
1021
1008
1022
-
If your optimistic state seems to be based on old data, it might be because the canonical state changed while your action was pending. React will update your optimistic value by re-running `reducer` with the new state.
1023
-
1024
-
If you're using the simple form without `reducer`, the value you passed directly replaces the state, which may not be what you want when the base state has changed. Consider using the `reducer` form to calculate the optimistic state relative to the current state.
1025
-
1026
-
See [Updating state based on the current state](#updating-state-based-on-current-state) for a detailed explanation.
1009
+
If your optimistic state seems to be based on old data, consider using an updater function or reducer to calculate the optimistic state relative to the current state.
1027
1010
1028
1011
```js
1029
1012
// May show stale data if state changes during action
0 commit comments