Implement Optimistic UI with the React useOptimistic hook in Next.js

Share this video with your friends

Send Tweet

"Optimistic UI" is a pattern for updating the page immediately with the data you have available, rather than waiting for the database query to resolve. In this lesson, we use React's useOptimistic hook to create an array of tweets that we can instantly update with our new state, when the user clicks the like button.

Code Snippets

Call useOptimistic hook

const [optimisticState, addOptimisticState] = useOptimistic(
  initialState,
  (currentState, newState) => {
    // merge state
    // return new state
  }
);

Add optimistic tweet

addOptimisticTweet({
  ...tweet,
  likes: tweet.likes - 1,
  user_has_liked_tweet: !tweet.user_has_liked_tweet,
});

Resources

Dominykas
Dominykas
~ 8 hours ago

Today, the useOptimistic code in the video throws an error (An optimistic state update occurred outside a transition or action. To fix, move the update to an action, or wrap with startTransition.) I was able to fix this (though I'm not sure if this is the best way) by:

  • wrapping the like button with a <form action={handleLikes}>
  • replacing <button onClick={handleLikes} with <button type="submit"

I also pulled addOptimisticTweet to fire before supabase.auth.getUser() because we know enough to update the UI without waiting for that promise.