Optimistic Updates in UI against a Server

Anyone have an idea/pointers on how do an optimistic ui update where, for example if I increment a counter locally, then push that to a server, then update the local value with the data from the server?

Basically a counter where the value is coming from the server but you where you publish the changes locally in the ui before you send then update with server value after you receive back the data.

This would an optimistic update if you were using graphql or relay.

Any guidance would be greatly appreciated. Thank you.

You could do it in two steps. First update the UI, then contact the server.

@mellson so I would need some type of global ui state and then update that state from the server? Update the ui state from the global state?

I assume you’re using react.

Not necessarily global, but yes you may need to use react context. I believe both SWR and React Query use this pattern.

They have a unique key for each hook which is necessary to pluck that state from context when you update locally and then update from the server response.

1 Like

It all depends. You don’t necessarily need a global solution. Which framework are you using, React? And have you settled on a state management solution?

But I would say that the optimistic UI updates itself is not something that requires anything special.

Let’s say you have a component with a counter. When you need to change the value you update the UI first and then send the new value to the server. Then you handle the response from the server when you get it.

So you could decouple the need for optimistic UI updates from your state management needs. Or look for a solution which solves both, such as Relay like you mentioned or React Query like @dangdennis says - both great solutions!

1 Like

Thank you for the feedback @mellson. Was just looking at react-query. Thought maybe I would do it without binding to a lib.