DEV Community

Cover image for ๐Ÿš€ New React Challenge: Instant UI with useOptimistic
ReactChallenges
ReactChallenges

Posted on

๐Ÿš€ New React Challenge: Instant UI with useOptimistic

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.

๐Ÿ”ฅ Start the Challenge Now


๐Ÿงฉ 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 useOptimistic hook together with startTransition to manage the optimistic state.

๐Ÿ’ก Notes

  • addOptimistic must be called inside startTransition โ€” otherwise React warns even though the UI still updates.
  • The passthrough state only needs to be a boolean (just the like value). The rest of data can stay static.
  • 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

  1. renders the app title
  2. renders both cards with labels
  3. starts with hearts not liked
  4. optimistically toggles the heart immediately and persists on success
  5. 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.

๐Ÿ”ฅ Start the Challenge Now

Top comments (0)