hardFrontend

How does `useOptimistic` enable optimistic UI in React 19?

704 views
01

Understand the problem

Showing an expected result instantly while an async action is in flight.

reactreact-19hooksoptimistic
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Explore the playground snippets

Optimistic message list
Run Playground
import { useState, useOptimistic, useRef } from 'react';

function send(text) {
  return new Promise((res) => setTimeout(() => res(text), 1000));
}

export default function App() {
  const [messages, setMessages] = useState(['Welcome!']);
  const [optimistic, addOptimistic] = useOptimistic(messages, (cur, text) => [
    ...cur,
    text + '  (sending…)',
  ]);
  const formRef = useRef(null);

  async function action(formData) {
    const text = formData.get('text');
    addOptimistic(text);        // shows instantly with the (sending…) tag
    formRef.current.reset();
    const sent = await send(text);
    setMessages((m) => [...m, sent]);   // real state replaces the optimistic one
  }

  return (
    <div style={{ fontFamily: 'sans-serif', padding: 24 }}>
      <ul>{optimistic.map((m, i) => <li key={i}>{m}</li>)}</ul>
      <form action={action} ref={formRef}>
        <input name="text" placeholder="Message" />
        <button>Send</button>
      </form>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.