Using the Optimistic Hook to implement optimistic updates
There are two ways to handle updates/mutations:
- Show a loading state and disable certain actions while it is loading
- Do an optimistic update, which immediately shows the result of the action on the client, while the mutation is still pending. Then, update the local state from the server state when the mutation finishes.
Depending on your use case, one or the other option will be a better fit. Usually, optimistic updates are great for fast-paced actions, such as a chat app. While a loading state without optimistic updates is better for critical actions, such as making a bank transfer.
The Optimistic Hook has the following signature:
const [optimisticState, addOptimistic] = useOptimistic(state, updateFn)
As we can see, it accepts a state
(usually, this is a server state) and an updateFn
function to process the update. Then, it returns an optimisticState
and an addOptimistic
function, which...