reactjsreduxrtk-query

What is difference between useQuery and initiate in RTK query?


When we are inside the selector, in order not to violate the rules of hooks, we can use the RTK query endpoint as follows:

1)useQuery

  const data = datsApi.endpoints.getData.useQuery(someProps)

2)initiate

  const data = await dispatch(datsApi.endpoints.getData.initiate(someProps))
  const { data } = data

But what is the difference between them, and when is it better to use each of the examples


Solution

  • initiate() is a Redux async thunk that triggers fetching data for that endpoint with that cache key argument.

    The useQuery hooks automatically dispatch that thunk as needed when a component mounts or you change the cache key argument to the hook, and also contain a useSelector call to retrieve that cache entry's data for the component.

    95% of the time, the useQuery hook is all you need.

    The initiate() thunk is really only needed when you have to trigger a request outside of a component, or in some other imperative logic.