{"id":3750,"date":"2026-11-21T20:28:39","date_gmt":"2026-11-21T12:28:39","guid":{"rendered":"http:\/\/www.biotechtubes.com\/blog\/?p=3750"},"modified":"2026-11-21T20:28:39","modified_gmt":"2026-11-21T12:28:39","slug":"how-to-handle-mutations-with-usemutation-4eb2-7bf49d","status":"publish","type":"post","link":"http:\/\/www.biotechtubes.com\/blog\/2026\/11\/21\/how-to-handle-mutations-with-usemutation-4eb2-7bf49d\/","title":{"rendered":"How to handle mutations with useMutation?"},"content":{"rendered":"<p>Hey guys, if you\u2019ve ever built a React app that needs to send data to a server\u2014like submitting a form, updating a user\u2019s profile, or deleting a product\u2014you\u2019ve probably run into useMutation. It\u2019s the go-to hook in the React Query toolkit (that\u2019s us, by the way\u2014we build custom hooks that take the pain out of server state management) and it\u2019s super powerful, but it\u2019s easy to trip over if you don\u2019t know the little tricks. I\u2019ve been talking to devs all week who\u2019re either just starting out with it or fighting weird bugs, so I figured I\u2019d spill all the tea on how to handle mutations like a pro. No jargon, no boring docs copy-paste, just real stuff I\u2019ve tested and actually use day-to-day. <a href=\"https:\/\/www.gscseatbelt.com\/hooks\/\">Hooks<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.gscseatbelt.com\/uploads\/202335941\/small\/2-inch-retractable-ratchet-straps7df2c5b1-0460-4d31-87c7-8c18ade91e27.jpg\"><\/p>\n<p>First, let\u2019s cut to the chase: what even is useMutation vs. useQuery? A lot of new devs mix these two up, and that\u2019s half the problem. useQuery is for getting data (fetching, reading)\u2014that\u2019s your \u201cGET\u201d calls. useMutation is for changing data (creating, updating, deleting)\u2014your \u201cPOST\u201d, \u201cPUT\u201d, \u201cDELETE\u201d calls. That seems simple, but when you\u2019re writing code, it\u2019s tempting to grab useQuery because you know it, and then wonder why your form isn\u2019t updating. Been there, done that, still have the t-shirt.<\/p>\n<p>Now, the first big mistake people make: not handling the mutation\u2019s lifecycle states. When you trigger a mutation, it doesn\u2019t just run and vanish. It has four key states that tell you exactly what\u2019s going on, and ignoring them leads to terrible UX. Let\u2019s list them out plain and simple: isIdle, isLoading, isSuccess, isError. IsIdle is before the mutation even runs\u2014like when your form is just sitting there, waiting to be submitted. IsLoading is when the request is out to the server, so you can show a little spinner and disable the submit button (that\u2019s basic, but I still see forms with double-submit buttons because devs forgot this). IsSuccess is when it worked\u2014time to clear the form, show a \u201cSuccess!\u201d toast, or refresh that list you just added an item to. IsError is when something went wrong\u2014maybe the server is down, or you forgot to add a required field, or the user doesn\u2019t have permission. If you don\u2019t show an error message here, users will stare at the screen like \u201cdid that even work?\u201d I once had a client whose login form had zero error handling, and half their users thought their password was broken because it didn\u2019t say \u201cwrong password\u201d or whatever. Don\u2019t be that guy.<\/p>\n<p>Wait, but what about variables? Like, when you submit a form, you\u2019re passing the form data into the mutation, right? The useMutation hook takes a function as its first argument\u2014that\u2019s your API call. So you\u2019ll set it up something like: const { mutate, isLoading, isError } = useMutation(async (formData) =&gt; { return axios.post(&#8216;\/api\/users&#8217;, formData) }). That\u2019s the basics, but here\u2019s a pro tip: never pass unnecessary variables. If your mutation only needs one value, like a user ID to delete, don\u2019t wrap it in an object. It\u2019s cleaner, less typing, and you avoid mistakes later. Also, if you need multiple values, name them clearly, not \u201cdata1\u201d or \u201cstuff\u201d \u2014 \u201cnewUserName\u201d or \u201cdeleteProductId\u201d is way easier to debug when your code is a month old and you forgot what you named things.<\/p>\n<p>Next up: handling side effects after success or error. This is where useMutation really shines, but it\u2019s also where a lot of people fumble. You can pass an object as the second argument to useMutation with onSuccess, onError, and onSettled callbacks. Let\u2019s break these down. OnSuccess runs only if the mutation works\u2014this is where you want to refresh your data if it\u2019s related, or redirect the user, or show a toast. For example, if you just added a blog post, you should refresh the list of posts so the user sees it immediately, no need to wait for a refetch interval. OnError runs only if it fails\u2014this is where you show that error message, maybe even parse the error response from the server (like if the API returns a specific message for duplicate emails) so you can display something useful, not just \u201cSomething went wrong\u201d. OnSettled runs whether it works or fails\u2014this is perfect for hiding that spinner, or re-enabling buttons, no matter what happens. I always put my loading state cleanup in onSettled, because I never want a stuck spinner. If I put it in onSuccess, it won\u2019t run if there\u2019s an error, and vice versa\u2014so onSettled is the safety net here.<\/p>\n<p>Wait, but what about mutate vs. mutateAsync? That\u2019s another common mix-up. Mutate is the \u201cfire and forget\u201d version\u2014it runs the mutation, but it doesn\u2019t return a promise, so you can\u2019t chain .then() or .catch() on it. MutateAsync is the promise-based one\u2014this is useful if you need to do something right after the mutation finishes, or if you want to wait for it to complete before doing another action. For example, if you have a form that submits, then redirects to a new page, you can use mutateAsync to redirect only after success: await mutateAsync(formData); router.push(&#8216;\/dashboard&#8217;). If you use mutate here, the redirect will happen immediately, before the request is done, which is bad news. I use mutateAsync most of the time now, only switching to mutate if I don\u2019t care about the result, like if I\u2019m logging an event to analytics after a button click.<\/p>\n<p>Another big one: invalidating queries after mutations. This is the whole point of React Query, right? When you change data, you need to update any queries that depend on that data so your app doesn\u2019t show stale data. Let\u2019s say you have a useQuery call that fetches a list of users: const { data: users } = useQuery(&#8216;users&#8217;, fetchUsers). When you add a new user, you run the createUser mutation. After that mutation succeeds, you need to tell React Query to invalidate the &#8216;users&#8217; query, so it refetches the fresh data. That\u2019s done with queryClient.invalidateQueries(&#8216;users&#8217;). If you skip this, your app will show the old list of users until the next background refetch, which could be minutes later. I learned this the hard way when building a todo app\u2014users would add a todo, but it wouldn\u2019t show up, and they thought the app was broken. Adding that invalidateQueries line fixed it immediately. Pro tip: you can even add filters to invalidate only specific queries, like invalidateQueries({ queryKey: [&#8216;users&#8217;, userId] }) if you only updated one user, not the whole list. Saves unnecessary network requests.<\/p>\n<p>What about retries? Sometimes mutations fail for silly reasons\u2014like a temporary network blip, or a server hiccup. useMutation lets you set retry options, just like useQuery, but wait\u2014wait a second. A lot of devs set retry: 3 on useMutation, but that\u2019s not always a good idea. If you\u2019re submitting a form that creates a user, you don\u2019t want to retry that request if it failed because of a duplicate email\u2014that would create two user accounts. So use retry wisely. The default is retry: 0 for mutations, which is usually safe, but you can customize it. Like, if you want to retry only on network errors, not on 4xx errors (which are client errors, like bad input), you can use a function: retry: (failureCount, error) =&gt; { return failureCount &lt; 2 &amp;&amp; error.response.status &gt;= 500 }. That way, you only retry if it\u2019s a server error, not a bad request from the user. Smart, right?<\/p>\n<p>Oh, and handling optimistic updates. That\u2019s a game-changer for UX. Optimistic updates are when you update your UI immediately as if the mutation worked, before the server even responds, so the user doesn\u2019t have to wait for the network. If the mutation fails, you roll back the UI to the old state. That makes apps feel way faster, like they\u2019re \u201csnappy\u201d. How do you do that with useMutation? It\u2019s simple. In the onMutate callback (wait, that\u2019s a special callback! Most people don\u2019t know about this), you can update your query data right away, and then return the old data so you can roll back if it fails. Let\u2019s say you\u2019re deleting a todo: const queryClient = useQueryClient(); const { mutate } = useMutation(deleteTodo, { onMutate: async (todoId) =&gt; { \/\/ Cancel any outgoing refetches so they don\u2019t overwrite our update await queryClient.cancelQueries(&#8216;todos&#8217;); \/\/ Snapshot the previous value const previousTodos = queryClient.getQueryData(&#8216;todos&#8217;); \/\/ Optimistically update the todos queryClient.setQueryData(&#8216;todos&#8217;, (old) =&gt; old.filter(todo =&gt; todo.id !== todoId)); \/\/ Return the snapshot to use later return { previousTodos }; }, \/\/ If the mutation fails, use the snapshot to roll back onError: (err, todoId, context) =&gt; { queryClient.setQueryData(&#8216;todos&#8217;, context.previousTodos); }, \/\/ Always refetch after error or success to make sure nothing\u2019s out of sync onSettled: () =&gt; { queryClient.invalidateQueries(&#8216;todos&#8217;); }, }). That\u2019s it! Your todo disappears instantly, the user sees it gone, and if for some reason the delete fails, it pops back. No spinners, no waiting, just smooth UI. I use optimistic updates for almost every write mutation now\u2014users go crazy for it.<\/p>\n<p>Wait, what about common pitfalls? Let\u2019s list the ones I see every single day. First, not cleaning up mutations if components unmount. If a component using useMutation unmounts before the mutation finishes, React might throw a warning about setting state on an unmounted component. How to fix that? You can use the isCancelable option, or use the mutation\u2019s cancel method in a useEffect cleanup. Or, even easier, use the mutation returned by useMutation and call mutate.cancel() in the component\u2019s cleanup. Another pitfall: overfetching or underfetching data in mutations. Make sure your mutation function only sends what the server needs\u2014no extra fields, no missing required fields. Too much data bogs down requests, too much missing data makes the server throw errors. Third, not testing error states. I\u2019ve seen so many apps where the error state is never tested, so when it goes live, it\u2019s broken. Test what happens when the server returns a 400, 500, network error, etc.<\/p>\n<p>And one last thing: if you\u2019re using our custom hooks (wait, that\u2019s us, right? We make hooks for React that simplify useMutation and all that server state stuff), we built a wrapper around useMutation that handles a lot of these edge cases out of the box\u2014like automatic error parsing, spinner state management, and pre-built optimistic update helpers. No need to write all that boilerplate every time.<\/p>\n<p>Look, at the end of the day, useMutation isn\u2019t rocket science. The main things are: know it\u2019s for write operations, use the lifecycle states for UX, handle success\/error\/settled callbacks, invalidate related queries, be careful with retries, and don\u2019t sleep on optimistic updates. I\u2019ve used these tricks on every project from small side hustles to enterprise apps, and they\u2019ve saved me hours of debugging and made apps way more reliable and user-friendly.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.gscseatbelt.com\/uploads\/202335941\/small\/heavy-duty-automative-tie-down-strapsaf279022-9aef-4f2c-b7cf-47bc2d4532cf.jpg\"><\/p>\n<p>If you\u2019re tired of fighting with React Query mutations, or you want custom hooks that streamline this whole process for your team, we can help. Our Hooks team builds tailored solutions that fit your app\u2019s needs, no generic one-size-fits-all garbage. We work with teams of all sizes, from solo devs to big corporations, to cut down on boilerplate and make your React code smoother. Hit us up to chat about how we can adapt useMutation (and all our other hooks) to your project\u2019s specific needs. We can walk through your current setup, point out where you\u2019re tripping up on mutations, and show you how our hooks can make handling data changes way less stressful.<\/p>\n<p><a href=\"https:\/\/www.gscseatbelt.com\/car-lashing\/lashings-auto\/\">Lashings Auto<\/a> References: React Query Official Docs, React Official Docs, MDN Web Docs for Fetch API, Frontend Masters React Query Course, Kent C. Dodds\u2019 React Hooks Guide<\/p>\n<hr>\n<p><a href=\"https:\/\/www.gscseatbelt.com\/\">Good Success Corp.<\/a><br \/>Good Success Corp. is one of the leading hooks manufacturers and suppliers in China. We warmly welcome you to buy cheap hooks for sale here from our factory. All customized products are with high quality and competitive price. Contact us for more details.<br \/>Address: NO.54, CHANG MA ROAD, CHANG HUA 500051, TAIWAN, R.O.C.<br \/>E-mail: sales@gscbelt.com<br \/>WebSite: <a href=\"https:\/\/www.gscseatbelt.com\/\">https:\/\/www.gscseatbelt.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey guys, if you\u2019ve ever built a React app that needs to send data to a &hellip; <a title=\"How to handle mutations with useMutation?\" class=\"hm-read-more\" href=\"http:\/\/www.biotechtubes.com\/blog\/2026\/11\/21\/how-to-handle-mutations-with-usemutation-4eb2-7bf49d\/\"><span class=\"screen-reader-text\">How to handle mutations with useMutation?<\/span>Read more<\/a><\/p>\n","protected":false},"author":552,"featured_media":3750,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3713],"class_list":["post-3750","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-hooks-4025-7c2920"],"_links":{"self":[{"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/posts\/3750","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/users\/552"}],"replies":[{"embeddable":true,"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/comments?post=3750"}],"version-history":[{"count":0,"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/posts\/3750\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/posts\/3750"}],"wp:attachment":[{"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/media?parent=3750"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/categories?post=3750"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.biotechtubes.com\/blog\/wp-json\/wp\/v2\/tags?post=3750"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}