Skip to content

Optimistic UI

Medium — good to knowFrontend

ELI5 — The Vibe Check

Optimistic UI means updating the interface BEFORE the server confirms the action succeeded. Click 'Like'? The heart turns red immediately. The API call happens in the background. If it fails (rare), you revert. The result? The app feels instant. No loading spinners for things that succeed 99% of the time. You're betting on success and rolling back on failure instead of waiting for certainty.

Real Talk

Optimistic UI is a pattern where the client immediately reflects the expected result of a mutation without waiting for server confirmation. If the server request fails, the client reverts to the previous state (rollback). This eliminates perceived latency for common operations. Frameworks like TanStack Query, Apollo Client, and SWR provide built-in optimistic update APIs. Critical consideration: proper error handling and state rollback.

Show Me The Code

// TanStack Query optimistic update
const likeMutation = useMutation({
  mutationFn: (postId) => api.likePost(postId),
  onMutate: async (postId) => {
    await queryClient.cancelQueries(['post', postId]);
    const previous = queryClient.getQueryData(['post', postId]);
    queryClient.setQueryData(['post', postId], (old) => ({
      ...old, liked: true, likes: old.likes + 1
    }));
    return { previous };
  },
  onError: (err, postId, context) => {
    queryClient.setQueryData(['post', postId], context.previous);
  },
});

When You'll Hear This

"Use optimistic UI for the like button — nobody wants to wait 200ms to see a heart." / "The chat sends messages optimistically and shows a retry button on failure."

Made with passive-aggressive love by manoga.digital. Powered by Claude.