Question presented to candidate: "A like button feels slow because the server takes a second and a half. How do you make it feel instant with useOptimistic, and what happens if the server rejects the like?"
What a strong answer should cover:
useOptimistic(state, updateFn)returns a value that shows an optimistic change while an action or transition is pending.- Call the optimistic setter inside a transition (a form action or
startTransition) together with the real action. - When the action finishes, React discards the optimistic value and shows the real state from the server.
- If the action fails or returns an unchanged state, the optimistic change disappears automatically; show an error from the action result.
useActionStateholds the server result and a pending flag; the two hooks are usually used together.
Clarifying questions expected:
- "Can the action fail, and how should that look?" β decides the error message and whether to retry.
- "Is the change safe to show before it is confirmed?" β optimistic UI suits likes and toggles, not payments.
Code / implementation expected: Yes β a like button with useOptimistic and useActionState.