Ever clicked a like button and watched it stall for a second while the server thinks about it? That tiny delay makes your app feel sluggish. React 19 ships useOptimistic to fix exactly that โ the UI changes before the server responds, and snaps back automatically if something goes wrong.
๐งฉ Overview
Learn React's useOptimistic hook by building instant heart toggles. Click the heart, see it turn red immediately, and let React handle the server in the background. If the request fails, the heart reverts on its own โ no manual rollback code.
โ Requirements
- Render two cards side by side: one labeled "Successful toggle" and another "Error toggle".
- Both cards start with the heart in a neutral (not liked) state.
- Clicking the heart on the successful toggle card must:
- Turn the heart red immediately, before the server responds.
- Keep the heart red after the server confirms the change.
- Clicking the heart on the error toggle card must:
- Turn the heart red immediately, before the server responds.
- Revert the heart to neutral after the server responds with an error.
- Use the
useOptimistichook together withstartTransitionto manage the optimistic state.
๐ก Notes
-
addOptimisticmust be called insidestartTransitionโ otherwise React warns even though the UI still updates. - The passthrough state only needs to be a
boolean(just the like value). The rest ofdatacan stay static. -
toggleFavoriteErroralways throws. A try/catch withconsole.errorprevents the red error overlay in dev without affecting the optimistic revert. - The data-testid attributes in the starter are already wired to the tests โ don't rename or remove them.
๐งช Tests
- renders the app title
- renders both cards with labels
- starts with hearts not liked
- optimistically toggles the heart immediately and persists on success
- reverts the heart on server error
If you've been writing setState(optimisticValue), then try/catch with manual rollbacks, useOptimistic deletes all that boilerplate. Give it a try and feel how snappy your UI can be.
Top comments (0)