React: useOptimistic

Problem:
Let's say we have a "๐Ÿ‘๐Ÿผ" button.
When the user clicks on it,

  • API call is made to save the value in the backend
  • A message "Liked" is displayed if the save was successful

But if the API call takes 5 seconds for the response, the UI looks laggy.

Solution:
useOptimistic hook: "Give me a temporary override of baseState while a transition is pending."
Note: It does NOT store an independent state.
It derives its value from the “base” (real) state.

Rules:
useOptimistic requires that there is some state that goes to ‘pending’ immediately after setting optimistic value

There are several ways to make the component go to ‘pending’ like using startTransition

When the pending transition stops, React stops using the optimistic value and re-renders using the real state value that your code updated.

Lifecycle
๐Ÿ‘๐Ÿผclicked -> transition starts -> optimistic value used -> component in "pending" state -> API returns (component is no more in "pending" state -> optimistic value is discarded -> component re-rendered with base state value

Details:

Button clicked: user action happens
Optimistic update applied: setOptimisticLiked
Transition starts: React marks component pending
UI shows optimistic value: user sees immediate effect
Async work completes: API call finishes
Pending ends: React no longer considers transition active
Optimistic value discarded: component falls back to real/base state
Component re-renders: shows actual state

“Pending” is a React internal flag, it allows optimistic overrides to survive.
The optimistic value itself is never synced automatically, it’s discarded when pending ends.
If async fails, it must be rolled back automatically.


Without useOptimistic
Like clicked
Transition started -> component moves to 'pending', lower priority, can be interrupted
'Liked' is displayed after 5 seconds


With useOptimistic

let's say there was an error, the useOptimistic will discard the optimistic value after it comes out of "pending" state and re-renders it with the actual state value


Optimistic updates are temporary UI tricks, but if theAPI call fails, the optimistic value needs to revert. React does not do this automatically.

Comments