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)