27

Trying to find an answer regarding react-query.

What's the difference between useQuery and useMutation?

From what i understand useQuery's are dependent calls.

useMutation are for posts that require updating the current state (cache invalidation, etc)

is that the correct assumption?

3 Answers 3

54

From Tanner Linsley:

The difference is the flow of data. useQuery is used to query async data, useMutation is used to mutate it. Or in the traditional CRUD speak:

  • Read: useQuery
  • Create/Update/Delete: useMutation

https://twitter.com/tannerlinsley/status/1324384797939003393

1
  • Generally yes, however you could still use useMutation to read data in some cases. Eg: Triggering a request on a user action.
    – Hiimdjango
    Commented Jan 16, 2023 at 1:41
13

Quoting Tanner Linsley (the creator of react-query)

useQuery is declarative, useMutation is imperative. Source: https://tkdodo.eu/blog/mastering-mutations-in-react-query#differences-to-usequery

Which means, useQuery runs when component is in focus, or is mounted; whereas useMutation has to be 'invoked'.

Also, as you may call same useQuery multiple times from multiple locations, that is not the case with useMutation.

1
0

useQuery is used when you want to fetch or read data from a server, while useMutation is used when you want to create, update, or delete data.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.