20

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?

chrisjlee
  • 21,691
  • 27
  • 82
  • 112

3 Answers3

42

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

Pierre-Adrien
  • 2,836
  • 29
  • 30
chrisjlee
  • 21,691
  • 27
  • 82
  • 112
  • Generally yes, however you could still use useMutation to read data in some cases. Eg: Triggering a request on a user action. – Hiimdjango Jan 16 '23 at 01:41
6

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.

Benjamin Cerf
  • 53
  • 1
  • 3
Sujit Y. Kulkarni
  • 1,186
  • 3
  • 22
  • 37
1

The best answer to this query which I found is : UseMutation: is used to create/update/delete data it's also used to re-fetch data. while UseQuery: is used to fetching data credit goes to:https://github.com/Avi98

Sajjad Ali
  • 47
  • 1
  • 6