DEV Community

melikdev
melikdev

Posted on

Optimistically updating the UI with the useOptimistic hook

In summary, useOptimistic is a React hook that displays a different state only while some asynchronous action is in progress. Most basic use case is to make asynchronous data visible on UI while it's still on it's way to the database. It's a great tool to build highly reactive UI's and increase the user experience. It's the most underrated React hook in my opinion.

SIMPLE USE CASE

In my little example app i implemented useOptimistic and Tanstack Query together to add users' comments on the UI before it reaches the database.

Image description

In my simple Invoice app i used useOptimistic hook for updating the status of the invoice.

First you have to import the hook:

import { useOptimistic } from 'react';

Use the useOptimistic hook with 2 arguments in it.

const [currentStatus, setCurrentStatus] = useOptimistic(
    invoice.status,
    (state, newStatus) => {
      return String(newStatus);
  }
);

Enter fullscreen mode Exit fullscreen mode

Then, write a simple function to handle a form action:

async function handleOnUpdateStatus(formData: FormData) {
  const originalStatus = currentStatus;
  setCurrentStatus(formData.get('status'));
  try {
    await updateStatusAction(formData);
  } catch (error) {
    setCurrentStatus(originalStatus);
  }
}
Enter fullscreen mode Exit fullscreen mode

Then add that function to your form using "onSubmit" event.

{AVAILABLE_STATUSES.map((status) => (
  <DropdownMenuItem key={status.id}>
    <form action={handleOnUpdateStatus}>
      <input type="hidden" name="id" value={invoice.id} />
      <input type="hidden" name="status" value={status.id} />
      <button>{status.label}</button>
    </form>
Enter fullscreen mode Exit fullscreen mode

The result:

Image description

Thank you for reading. Have fun.

Top comments (0)