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
tsfunction useOptimistic(state: T, updateState: (currentState: T, action: N) => T): [T, (action: N) => void]
Parameters
| Name | Type |
|---|---|
state | T |
updateState | (currentState: T, action: N) => T |
Returns: [T, (action: N) => void]
Diagram
mermaidgraph 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
tsximport { 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?