Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readReact

Add optimistic UI with useOptimistic

Show a like while a React action saves it and return to the confirmed value if the request fails.

Show a like as soon as the user presses the button. While the save is pending, disable the button. If the save fails, show the last confirmed state and a retry message.

Keep the confirmed value separate

Give useOptimistic the confirmed boolean. Inside the action, tell React what to show for the duration of the save. Update the confirmed value after success and leave it alone after failure.

The example starts unliked. Mount LikeDemo to try it. The checkbox makes the next save fail so you can see the rollback without a network connection.

import { useOptimistic, useState, useTransition } from 'react'

function LikeButton({ saveLiked }) {
  const [liked, setLiked] = useState(false)
  const [shownLiked, showLiked] = useOptimistic(liked)
  const [saving, startTransition] = useTransition()
  const [error, setError] = useState('')

  function toggle() {
    const next = !liked
    setError('')
    startTransition(async () => {
      showLiked(next)
      try {
        const saved = await saveLiked(next)
        startTransition(() => setLiked(saved))
      } catch {
        startTransition(() => setError('Could not save. Try again.'))
      }
    })
  }

  return (
    <>
      <button type="button" aria-pressed={shownLiked} disabled={saving} onClick={toggle}>
        <span aria-hidden="true">{shownLiked ? '♥' : '♡'}</span> Like
      </button>
      <p role="status">{error}</p>
    </>
  )
}

export default function LikeDemo() {
  const [fail, setFail] = useState(false)
  return (
    <>
      <label>
        <input type="checkbox" checked={fail} onChange={(event) => setFail(event.target.checked)} />
        Fail the save
      </label>
      <LikeButton saveLiked={async (next) => {
        await new Promise((resolve) => setTimeout(resolve, 600))
        if (fail) throw new Error('Save failed')
        return next
      }} />
    </>
  )
}

With the box checked, the heart fills during the save, then empties again and an error message appears.

diagram

Which value the button shows

For a note that starts unliked, success confirms the like and failure returns the button to unliked.

Let the action finish

Call showLiked inside the transition so React knows which pending work owns that temporary value. Wrap the setters after await in startTransition too. React needs that call to treat those updates as part of a transition.

The button disables while saving to keep one request in flight. The label stays Like and aria-pressed conveys the same state as the heart. Try again with Fail the save unchecked. The heart stays filled after the action ends because the confirmed value changed.

Send the desired boolean to a real endpoint and store the value it confirms. If a request times out after the server writes the value, refetch the confirmed state when you need to resolve the ambiguity.