All the steps for Optimistic Updates in React Query

Just a guy who loves to write code and watch anime.
Search for a command to run...

Just a guy who loves to write code and watch anime.
No comments yet. Be the first to comment.
Qualities that make outstanding builders.

Bipedal vs quadrupedal: how many legs This is about the number of legs the creature walks on. Bipedal. Two legs. Humans, ostriches, T-rex, kangaroos, most fantasy humanoids. Quadrupedal. Four legs. Do

Intro You hear "lerp" and "smoothstep" everywhere in game dev. They sound like math jargon. They're not. Both are small tools that do the same job: smoothly move from one value to another. The problem

What is Kinematics Kinematics is the math field. It's the study of how things move without worrying about forces (which would be dynamics). FK and IK are the two branches: forward kinematics and inver

Intro Textures are usually the biggest cost in a 3D scene. Memory, bandwidth, and load time all get eaten by them. Resizing them is the obvious lever. There's more. This post is about the less obvious

function useToggleTodo(id, sort) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: () => toggleTodo(id),
onMutate: async () => {
// 1. Cancel outgoing queries
await queryClient.cancelQueries({
queryKey: ['todos', 'list', { sort }]
})
// 2. Store previous state
const snapshot = queryClient.getQueryData(['todos', 'list', { sort }])
// 3. Set new optimistic state
queryClient.setQueryData(
['todos', 'list', { sort }],
(prev) => prev?.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
)
)
// 4. Return rollback function
return () => {
queryClient.setQueryData(['todos', 'list', { sort }], snapshot)
}
},
onError: (error, variables, rollback) => {
// 5. Rollback if error
rollback?.()
},
onSettled: () => {
// 6. Invalidate to sync with server
queryClient.invalidateQueries(['todos', 'list'])
}
})
}
Step 1 (Cancel): Prevents race conditions where a background refetch overwrites your optimistic update
Steps 2-4 (Snapshot/Update/Return): Immediate UI feedback + rollback capability
Step 5 (Rollback): If server says "nope", undo the optimistic change
Step 6 (Invalidate): Even on success, double-check with server to stay in sync
The magic is in onMutate → it runs before the network request, so users see instant feedback. Then you handle the server response afterwards.