WhoBuilt

Fast ecommerce with optimistic UI and Next.js

Aug 22, 2024· 3 min· 28K views·Watch on YouTube

Lee Robinson from leerob explains how to make ecommerce cart interactions feel instant with React’s optimistic UI tools and Next.js.

Why optimistic cart updates matter

Adding, changing, or removing a cart item often triggers a loading state while the server responds. Optimistic UI updates the cart immediately, which can make those interactions feel faster.

Update the cart with useOptimistic

React’s useOptimistic hook helps manage UI changes before a server action completes. In the example, a useCart context provides the cart state and a reducer-style function for adding or updating items across the app.

Save changes with server actions

After the immediate update, the client action calls a React server action that saves the item to Shopify. The same pattern supports quantity controls: update the UI optimistically, then call updateItemQuantity.

Keep interactions responsive on slow networks

With network throttling set to 3G, the server request takes about two seconds, but the cart still updates immediately. Robinson describes this as combining client and server tools to improve the user experience.

Takeaways

  • Use optimistic updates for cart actions where users benefit from immediate feedback.
  • Keep shared cart state in a context so multiple parts of the app can reuse it.
  • Apply the UI update first, then persist the change with a server action.
  • Test perceived responsiveness under simulated network latency.

Mentioned in this talk

Search inside this talk

What was claimed 5

  • feature
    React: optimistic state updates
    optimistic state updates
    “React has some new features, namely the `useOptimistic` hook”
    YouTube
    Unverified1 source· Talk
  • feature
    useCart: Provides shared access to optimistically updated cart state
    “then read it using the same `useCart` hook in other parts of our application”
    YouTube
    Unverified1 source· Talk
  • uses
    “Inside it, we're using React's `useOptimistic` hook.”
    YouTube
    Unverified1 source· Talk
  • integrates with
    React integrates with Shopify
    “The React server action is called `addItem`. It goes to Shopify and saves that value”
    YouTube
    Unverified1 source· Talk
  • metric
    optimistic UI: About two seconds of simulated latency on 3G while the UI updates immediately
    “it's taking about two seconds. Still, it feels really snappy when I click it.”
    YouTube
    Unverified1 source· Talk

Related talks