Showing the result before it is saved
When a form reaches a server, the round-trip takes time. If the UI waits for the reply before showing anything, the app feels slow even when the request is quick. An optimistic update shows the result you expect straight away, then reconciles with the real one when it arrives.
useOptimistic takes the real state and a reducer, and returns the optimistic
state plus a function to update it:
const [optimisticLikes, addOptimisticLike] = useOptimistic(
likes,
(current, delta) => current + delta,
);
Call the updater inside an action, before the await:
async function like() {
addOptimisticLike(1);
await save();
}
React renders the optimistic value at once. When the action settles, the optimistic entry is dropped and the component re-renders from the real state, so the value only keeps if the save really succeeded. The optimistic value lives only while the action is pending: it is a preview, not a second source of truth.
Your job is to apply an optimistic update while a form action runs in App.jsx.
Challenge
A like button should show its result at once, before the server answers. Export an
App component from App.jsx that keeps a like count in useState, starts at
0, and shows it as Likes: <n> in a paragraph. Use useOptimistic for the
count, and a form action — triggered by a submit button labelled Like — that
adds one optimistically, then commits one to the real state.
The Test clicks Like and expects Likes: 1 before the action settles, and
still Likes: 1 once it has. The starter never updates, so the Test fails.