When you click Send in a chat app, you donโt want to wait for the server to respond before seeing your message appear.
React 19 introduces useOptimistic
, a hook that lets you update the UI immediately while a background action (like sending a message) is in progress.
This makes apps feel fast and responsive.
โ
What is useOptimistic
?
useOptimistic
lets you show a temporary state (optimistic state) while an async action is underway.
Syntax:
const [optimisticState, addOptimistic] = useOptimistic(
state, // confirmed state
(current, val) => newState // function to compute optimistic state
);
-
state
โ the confirmed state. -
optimisticState
โ what is shown while the async action runs. -
addOptimistic(val)
โ call this to update the UI optimistically.
๐ฅ Simple Chat Example
import React, { useState } from "react";
import { useOptimistic, startTransition } from "react";
export default function App() {
const [messages, setMessages] = useState([]);
const [optimisticMessages, addMessage] = useOptimistic(
messages,
(state, newMsg) => [...state, { text: newMsg, sending: true }]
);
function handleSend(msg) {
addMessage(msg); // show instantly
startTransition(async () => {
await new Promise((resolve) => setTimeout(resolve, 1000)); // fake API
setMessages(prev => [...prev, { text: msg }]); // confirm
});
}
return (
<div style={{ padding: "2rem", fontFamily: "sans-serif" }}>
<h2>Chat</h2>
<ul>
{optimisticMessages.map((m, i) => (
<li key={i}>
{m.text} {m.sending && "(Sending...)"}
</li>
))}
</ul>
<button onClick={() => handleSend("Hello!")}>Send Message</button>
</div>
);
}
๐ง How it works
-
addMessage("Hello!")
โ immediately shows the message in the UI with(Sendingโฆ)
. -
startTransition
โ simulates sending the message in the background. -
setMessages
โ confirms the message once the async task finishes.
๐ฏ Why use useOptimistic
?
- Makes UI feel instant.
- Great for likes, comments, forms, or chat messages.
- Users see immediate feedback even if the server is slow.
This small hook makes your React apps snappy and responsive with minimal code.
Top comments (0)