react-query - What's the difference between useQuery and useMutation hook?
Asked Answered
R

3

26

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?

Robledo answered 5/11, 2020 at 16:8 Comment(0)
R
53

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

Robledo answered 5/11, 2020 at 19:58 Comment(1)
Generally yes, however you could still use useMutation to read data in some cases. Eg: Triggering a request on a user action.Aiken
N
12

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.

Ninny answered 15/2, 2023 at 13:58 Comment(1)
Source : tkdodo.eu/blog/…Rattle
O
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.

Overhear answered 30/4 at 12:51 Comment(1)
i t;hink so i am correctOverhear

© 2022 - 2024 — McMap. All rights reserved.