Skip to content

useOptimistic

reference
1 min readUpdated

Kind: Function

Source: src/jsx/dom/hooks/index.ts

Part of: Jsx

This hook returns the current state and a function to update the state optimistically The current state is updated optimistically and then reverted to the original state when all actions are resolved

useOptimistic returns the current optimistic state and a function that applies an optimistic update. Updates are shown immediately while related actions are pending, then the state returns to the original value after those actions resolve.

Signature

ts
function useOptimistic(state: T, updateState: (currentState: T, action: N) => T): [T, (action: N) => void]

Parameters

NameType
stateT
updateState(currentState: T, action: N) => T

Returns: [T, (action: N) => void]

Diagram

mermaid
graph LR
  A[Current state] --> B[useOptimistic]
  B --> C[Optimistic state]
  D[Pending action] --> E[Apply optimistic update]
  E --> C
  D --> F[Action resolves]
  F --> A

Usage

tsx
import { useOptimistic } from "react";

function LikeButton({ likes }: { likes: number }) {
  const [optimisticLikes, addOptimisticLike] = useOptimistic(
    likes,
    (currentLikes, increment: number) => currentLikes + increment,
  );

  async function handleLike() {
    addOptimisticLike(1);

    await fetch("/api/likes", {
      method: "POST",
    });
  }

  return (
    <button onClick={handleLike}>
      Likes: {optimisticLikes}
    </button>
  );
}

AI Coding Instructions

  • Pass the confirmed server or parent state as the base value for useOptimistic.
  • Define the update function as a pure function that derives optimistic state from the current state and action input.
  • Call the optimistic update function as part of the action that performs the related asynchronous work.
  • Do not treat optimistic state as the source of truth; update the base state when the action result is available.
  • Handle action failures so the surrounding state remains consistent after optimistic updates are reverted.

Was this page helpful?

Download as PDF
useOptimistic — Hono (narrator proof)