DEV Community

arafatruetbd
arafatruetbd

Posted on

๐Ÿš€ React 19 โ€“ Optimistic UI with `useOptimistic`

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
);
Enter fullscreen mode Exit fullscreen mode
  • 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>
  );
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿง  How it works

  1. addMessage("Hello!") โ†’ immediately shows the message in the UI with (Sendingโ€ฆ).
  2. startTransition โ†’ simulates sending the message in the background.
  3. 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)