Optimistic and pessimistic manual cache update in Redux Toolkit
In Redux Toolkit (RTK), optimistic and pessimistic cache updates refer to two different approaches for handling cache updates in a Redux store.
With optimistic updates, the cache is updated immediately in response to a user action, such as submitting a form or clicking a button, before the action is sent to the server. This can provide a more responsive and interactive user experience, as the updated data is immediately visible on the screen. However, if the server responds with an error, the client-side cache may need to be rolled back or updated to reflect the server state.
Example of optimistic update:
updatePostMeta: builder.mutation({
query: ({id, accountId}) => ({
url: `/users/${accountId}/post/${id}`,
method: 'PATCH',
headers: {'Authorization': `Bearer ${getToken()}`},
body: {"meta": {/* some object with metatags */}},
}),
async onQueryStarted({id, accountId, ...patch}, {dispatch, queryFulfilled}) {
const patchResult = dispatch(
clusterApi.util.updateQueryData('getPostById', {id, accountId}, (draft) => {
Object.assign(draft, patch)
})
)
try {
await queryFulfilled
} catch {
patchResult.undo()
}
},
});
With pessimistic updates, the cache is only updated after the server has successfully responded to the user action. This can help ensure that the client-side and server-side data are always in sync, as the client is always waiting for the server’s response before updating the cache. However, this can also result in slower and less responsive user interfaces, as the user has to wait for the server to respond before seeing any changes on the screen.
Example of pessimistic update:
updatePostMeta: builder.mutation({
query: ({id, accountId}) => ({
url: `/users/${accountId}/post/${id}`,
method: 'PATCH',
headers: {'Authorization': `Bearer ${getToken()}`},
body: {"meta": {/* some object with metatags */}},
}),
async onQueryStarted({ id, accountId, ...patch }, { dispatch, queryFulfilled }) {
try {
const { data: updatedPost } = await queryFulfilled
const patchResult = dispatch(
api.util.updateQueryData('getPost', {id, accountId}, (draft) => {
Object.assign(draft, updatedPost)
})
)
} catch {}
},
});
In summary, optimistic updates prioritize a more responsive user interface, while pessimistic updates prioritize consistency between the client-side and server-side data. The choice between optimistic and pessimistic updates depends on the specific requirements of your application and the user experience you want to provide.