# 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.
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