useMutation xử lý write operations (POST/PUT/DELETE) — khác useQuery chỉ đọc.
Cung cấp mutate() (fire-and-forget) hoặc mutateAsync() (trả về Promise).
States: isPending, isError, isSuccess, data, error.
Optimistic update flow:
onMutate: cancel ongoing queries, snapshot data cũ, set cache mới ngay → UI cập nhật tức thì.onError: nhận snapshot từ onMutate context, rollback cache.onSettled: invalidate queries để sync với server
Ví dụ thực tế: user like bài viết → heart đỏ ngay lập tức (optimistic), nếu API fail → rollback heart về trắng.
useMutation handles write operations (POST/PUT/DELETE) — unlike useQuery which only reads.
Provides mutate() (fire-and-forget) or mutateAsync() (returns a Promise).
States: isPending, isError, isSuccess, data, error.
Optimistic update flow:
onMutate: cancel ongoing queries, snapshot old data, immediately set new cache → UI updates instantly.onError: receive snapshot from onMutate context, rollback cache.onSettled: invalidate queries to sync with server
Practical example: user likes a post → heart turns red immediately (optimistic); if the API fails → rollback the heart to white.