Optimistic updates
The entire trick: UI is assuming the server will respond with a success, and updates the UI accordingly. This feature is a part of React. Next 14 introduces this feature as production ready.
Implementation
src/app/optimistic/page.jsx
import OptimisticList from "../../components/OptimisticList";
export default function Optimistic() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<OptimisticList />
</main>
);
}
src/components/List.jsx
'use client'
import { useOptimistic, useState } from 'react';
const wait = (value, time) =>
new Promise((resolve) => setTimeout(() => resolve(value), time));
export default function OptimisticList() {
const [items, setItems] = useState([]);
const [optimisticItems, setOptimisticItems] = useOptimistic(items);
const formAction = async (formData) => {
const label = formData.get('label');
setOptimisticItems((state) => [...state, `${label} - optimistic`]);
await wait(label, 2000);
await fetch('http://google.com', {mode: 'no-cors'});
setItems((state) => [...state, `${label} - server`]);
}
console.log({items, optimisticItems});
return (
<>
<form
className='mt-4'
action={formAction}
>
<input name="label" className="p-2 rounded mr-1"/>
<button type="submit" className="p-2 bg-green-500 rounded mr-1">Add</button>
</form>
<ul>
{optimisticItems.map((label, index) => (
<li key={index}>{label}</li>
))}
</ul>
</>
);
}
Request Queuing
tip
If the user will hit "Add" button multiple times before API responds, we are still safe as the requests are going to be queued and executed in correct order.

