# Use optimistic > Learn React's `useOptimistic` hook by building instant heart toggles that update the UI before the server responds — and revert automatically when requests fail. - Difficulty: intermediate - Tags: useOptimistic, startTransition, react 19 - Estimated time: 30 minutes - Tests: 7 - Requires subscription: yes ## 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 `useOptimistic` hook together with `startTransition` to 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 `addOptimistic` outside the transition logs React's "optimistic state update occurred outside a Transition" warning. The global `startTransition` is enough here; `useTransition` is only needed for a pending state. - The second argument of `useOptimistic` is optional. Without a reducer, React uses the value passed to the setter as the optimistic state, so `useOptimistic(like)` is enough. - The passthrough state only needs to be a `boolean` (just the like value). The rest of `data` can stay static. - Read the current optimistic value (`optimisticLike`) to calculate the next one, and pass that same value to the server call. Using the confirmed `like` state in the handler sends stale data when the user clicks twice before the first request resolves. - `toggleFavoriteError` always throws. A try/catch with `console.error` prevents 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 01. renders the app title 02. renders both cards with labels 03. starts with hearts not liked 04. optimistically toggles the heart immediately and persists on success 05. reverts the heart on server error 06. uses the latest optimistic value on a fast success double-click 07. uses the latest optimistic value on a fast error double-click