# 5230 MINUse optimistic
# 52
30 MIN
Overview
Learn React's useOptimistic hook by building instant heart toggles that update the UI before the server responds — and revert automatically when requests fail.
Solution preview
Here's the result you'll build by completing this challenge.
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. - If the heart is clicked again while a request is still pending, the next click must undo the previous optimistic change. After two quick clicks, the heart must return to its original state once both requests finish.
Notes
- Calling
addOptimisticoutside the transition logs React's "optimistic state update occurred outside a Transition" warning. The globalstartTransitionis enough here;useTransitionis only needed for a pending state. - The second argument of
useOptimisticis optional. Without a reducer, React uses the value passed to the setter as the optimistic state, souseOptimistic(like)is enough. - The passthrough state only needs to be a
boolean(just the like value). The rest ofdatacan stay static. - Read the current optimistic value (
optimisticLike) to calculate the next one, and pass that same value to the server call. Using the confirmedlikestate in the handler sends stale data when the user clicks twice before the first request resolves. 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
- uses the latest optimistic value on a fast success double-click
- uses the latest optimistic value on a fast error double-click