useOptimistic: Updating the UI Instantly

Core Definition

useOptimistic() is a React Hook that lets you apply an optimistic update to state while an asynchronous action is in progress. It accepts the current state and an update function that describes the optimistic change. The state is immediately updated optimistically, and once the asynchronous action completes, the state is reconciled with the actual result.

Key Characteristics

  • Immediate UI Feedback: updates the UI instantly without waiting for the server response, making the application feel faster and more responsive.
  • Automatic Reversion: if the asynchronous action fails, the UI automatically reverts to the last known actual state, ensuring data consistency.
  • State Management: it takes the current state and an update function, returning an optimistic version of the state that you can render in your component.

When to use?

Use it for actions that have a high likelihood of success and where immediate feedback is beneficial. Common cases include submitting forms (like sending a message), liking a post, or adding an item to a shopping cart.

Examples

  • Optimistic Form Submission: this example shows a message list that optimistically adds a new message to the UI while the server request is in progress. If the request fails, the message is removed.