Hey guys, if you’ve ever built a React app that needs to send data to a server—like submitting a form, updating a user’s profile, or deleting a product—you’ve probably run into useMutation. It’s the go-to hook in the React Query toolkit (that’s us, by the way—we build custom hooks that take the pain out of server state management) and it’s super powerful, but it’s easy to trip over if you don’t know the little tricks. I’ve been talking to devs all week who’re either just starting out with it or fighting weird bugs, so I figured I’d spill all the tea on how to handle mutations like a pro. No jargon, no boring docs copy-paste, just real stuff I’ve tested and actually use day-to-day. Hooks

First, let’s cut to the chase: what even is useMutation vs. useQuery? A lot of new devs mix these two up, and that’s half the problem. useQuery is for getting data (fetching, reading)—that’s your “GET” calls. useMutation is for changing data (creating, updating, deleting)—your “POST”, “PUT”, “DELETE” calls. That seems simple, but when you’re writing code, it’s tempting to grab useQuery because you know it, and then wonder why your form isn’t updating. Been there, done that, still have the t-shirt.
Now, the first big mistake people make: not handling the mutation’s lifecycle states. When you trigger a mutation, it doesn’t just run and vanish. It has four key states that tell you exactly what’s going on, and ignoring them leads to terrible UX. Let’s list them out plain and simple: isIdle, isLoading, isSuccess, isError. IsIdle is before the mutation even runs—like 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’s basic, but I still see forms with double-submit buttons because devs forgot this). IsSuccess is when it worked—time to clear the form, show a “Success!” toast, or refresh that list you just added an item to. IsError is when something went wrong—maybe the server is down, or you forgot to add a required field, or the user doesn’t have permission. If you don’t show an error message here, users will stare at the screen like “did that even work?” I once had a client whose login form had zero error handling, and half their users thought their password was broken because it didn’t say “wrong password” or whatever. Don’t be that guy.
Wait, but what about variables? Like, when you submit a form, you’re passing the form data into the mutation, right? The useMutation hook takes a function as its first argument—that’s your API call. So you’ll set it up something like: const { mutate, isLoading, isError } = useMutation(async (formData) => { return axios.post(‘/api/users’, formData) }). That’s the basics, but here’s a pro tip: never pass unnecessary variables. If your mutation only needs one value, like a user ID to delete, don’t wrap it in an object. It’s cleaner, less typing, and you avoid mistakes later. Also, if you need multiple values, name them clearly, not “data1” or “stuff” — “newUserName” or “deleteProductId” is way easier to debug when your code is a month old and you forgot what you named things.
Next up: handling side effects after success or error. This is where useMutation really shines, but it’s 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’s break these down. OnSuccess runs only if the mutation works—this is where you want to refresh your data if it’s 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—this 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 “Something went wrong”. OnSettled runs whether it works or fails—this 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’t run if there’s an error, and vice versa—so onSettled is the safety net here.
Wait, but what about mutate vs. mutateAsync? That’s another common mix-up. Mutate is the “fire and forget” version—it runs the mutation, but it doesn’t return a promise, so you can’t chain .then() or .catch() on it. MutateAsync is the promise-based one—this 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(‘/dashboard’). 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’t care about the result, like if I’m logging an event to analytics after a button click.
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’t show stale data. Let’s say you have a useQuery call that fetches a list of users: const { data: users } = useQuery(‘users’, 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 ‘users’ query, so it refetches the fresh data. That’s done with queryClient.invalidateQueries(‘users’). 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—users would add a todo, but it wouldn’t 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: [‘users’, userId] }) if you only updated one user, not the whole list. Saves unnecessary network requests.
What about retries? Sometimes mutations fail for silly reasons—like a temporary network blip, or a server hiccup. useMutation lets you set retry options, just like useQuery, but wait—wait a second. A lot of devs set retry: 3 on useMutation, but that’s not always a good idea. If you’re submitting a form that creates a user, you don’t want to retry that request if it failed because of a duplicate email—that 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) => { return failureCount < 2 && error.response.status >= 500 }. That way, you only retry if it’s a server error, not a bad request from the user. Smart, right?
Oh, and handling optimistic updates. That’s 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’t 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’re “snappy”. How do you do that with useMutation? It’s simple. In the onMutate callback (wait, that’s a special callback! Most people don’t 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’s say you’re deleting a todo: const queryClient = useQueryClient(); const { mutate } = useMutation(deleteTodo, { onMutate: async (todoId) => { // Cancel any outgoing refetches so they don’t overwrite our update await queryClient.cancelQueries(‘todos’); // Snapshot the previous value const previousTodos = queryClient.getQueryData(‘todos’); // Optimistically update the todos queryClient.setQueryData(‘todos’, (old) => old.filter(todo => 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) => { queryClient.setQueryData(‘todos’, context.previousTodos); }, // Always refetch after error or success to make sure nothing’s out of sync onSettled: () => { queryClient.invalidateQueries(‘todos’); }, }). That’s 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—users go crazy for it.
Wait, what about common pitfalls? Let’s 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’s cancel method in a useEffect cleanup. Or, even easier, use the mutation returned by useMutation and call mutate.cancel() in the component’s cleanup. Another pitfall: overfetching or underfetching data in mutations. Make sure your mutation function only sends what the server needs—no 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’ve seen so many apps where the error state is never tested, so when it goes live, it’s broken. Test what happens when the server returns a 400, 500, network error, etc.
And one last thing: if you’re using our custom hooks (wait, that’s 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—like automatic error parsing, spinner state management, and pre-built optimistic update helpers. No need to write all that boilerplate every time.
Look, at the end of the day, useMutation isn’t rocket science. The main things are: know it’s for write operations, use the lifecycle states for UX, handle success/error/settled callbacks, invalidate related queries, be careful with retries, and don’t sleep on optimistic updates. I’ve used these tricks on every project from small side hustles to enterprise apps, and they’ve saved me hours of debugging and made apps way more reliable and user-friendly.

If you’re 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’s 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’s specific needs. We can walk through your current setup, point out where you’re tripping up on mutations, and show you how our hooks can make handling data changes way less stressful.
Lashings Auto References: React Query Official Docs, React Official Docs, MDN Web Docs for Fetch API, Frontend Masters React Query Course, Kent C. Dodds’ React Hooks Guide
Good Success Corp.
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.
Address: NO.54, CHANG MA ROAD, CHANG HUA 500051, TAIWAN, R.O.C.
E-mail: sales@gscbelt.com
WebSite: https://www.gscseatbelt.com/