Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use useMutation in React Query?

Tags:

react-query

I am new to react query.

I found out that using useQuery can reduce requests by caching.

But it's hard to understand why I use useMutation.

axios.post('/user', { name, ... })
  .then(res => console.log(res))
  .catch(err => console.log(err);
const { mutate, isLoading, ... } = useMutation(fetcher, {
  onSuccess: (res) => {
    console.log(res);
  },
  onError: (err) => {
    console.log(err);
  }
});

Both codes handle successful requests and errors.

Isn't queryClient.invalidateQueries('queryKey'); also covered by axios then() function?

What's the difference between the two?

like image 982
Hyeonjun Jeong Avatar asked Jun 26 '26 18:06

Hyeonjun Jeong


1 Answers

Outside of returning useful mutation states (isPending, isSuccess, error), as of React Query v5 you can now track a mutation from another component, with help of useMutationState. In some cases this can eliminate the need for a store/context to expose these states to other components, or passing them down as props, as any component can just access any mutation with useMutationState, provided you specified the mutationKey

like image 173
Jo Gro Avatar answered Jul 01 '26 02:07

Jo Gro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!