Cover image for Optimistic UI Trick Revealed!

Optimistic UI Trick Revealed!

ghackdev profile image ghack.dev ・2 min read

Fake it, 'til you make it.

Suddenly I remember that quote when I'm talking about Optimistic UI. Before I understand what Optimistic UI is, I just wondering that how a response could be that fast. 😳 For example, look at Instagram like UI.


There is no boring loading icon. When we press the like button, it will immediately liked the post. That's awesome right? 😲

When a Magician 🎩 performs a trick, we could be easily amazed until someone revealed the trick.

So, How Optimistic UI works?

Let's reveal the secret behind the Optimistic UI trick.

Optimistic UI is a pattern that you can use to simulate the results of a mutation and update the UI even before receiving a response from the server. Once the response is received from the server, the optimistic result is thrown away and replaced with the actual result. -- Apollo GraphQL

"Simulate the results" means that we need to fake the response first, before we receive the real one. That's it. 💁‍♂️


We could implement this pattern easily using Apollo Client. This is one of the benefits of using GraphQL because the request and response are defined earlier in the Query and Mutation schema, we could easily fake the response while ensuring that the data becomes consistent with the actual response when it arrives.

const LIKE_POST = gql`
  mutation LikePost($postID: ID!) {
    likePost(postID: $postID) {

const Posts = () => {
  const username = useSelector(state => state.auth.username)
  const [mutate] = useMutation(LIKE_POST)
  return (
      updateComment={({ id, likers }) =>
          variables: { postID: id },
          optimisticResponse: {
            __typename: "Mutation",
            likePost: {
              __typename: "Post",
              likers: [...likers, username]

Now, this trick couldn't amazed us anymore. 😅

Posted on by:

ghackdev profile



Free programming, web and mobile app development courses and tutorials.


markdown guide

but how you process that optimisticResponse? like reading it?