"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.
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,
});