1. 17
    Implement Optimistic UI with the React useOptimistic hook in Next.js
    4m 49s

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

InstructorJon Meyers

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