What is useMutation and how does it work?
You must be aware by now that mutations allow you to perform updates to your server state. These updates can be things such as creating data, removing data, or editing your data.
To allow you to perform mutations on your server data, React Query created a hook called useMutation
.
Now, unlike useQuery
, which under the default circumstances runs your query automatically as soon as the component using it renders or some dependencies of it change, useMutation
will only run your mutation when you call one of the functions it returns from the hook instantiation called mutate
.
To use the useMutation
hook, you have to import it like this:
import { useMutation } from '@tanstack/react-query';
Once it is imported, you can use it to define your mutation. Here is the useMutation
syntax:
const mutation = useMutation({ mutationFn: <InsertMutationFunction> })
As you can see from the preceding snippet...