Apollo Client useLazyQuery query function vs refetch

when I use useLazyQuery(), it returns query function and refetch. Is there a difference in its behavior?

refetch function is undefined until query function is initially called so I need to do the following:

const [getUsers, {data, called, refetch}] = useLazyQuery(SOME_QUERY)

const fetchFn = called ? refetch : getUsers
// use fetchFn when needed

Can’t I simply use getUsers everywhere I need to fetch?

1 Like

I’ve been wondering this as well. I can see in the code that the implementations are distinct but it’s still not clear to me what the differences are.

From experience I’ve found that you can’t treat the lazy fetch function as refetch, but you can use the refetch function for the initial fetch and ignore the lazy fetch function.

I’d love to hear an explanation for why this is the case from someone with more in depth knowledge.

Hey there :wave:

One of the biggest differences between the two functions is that refetch will guarantee a network request, whereas the query function returned by useLazyQuery will adhere to the fetchPolicy you have set. For example, if you use a cache-first fetch policy and call getUsers with data in the cache, you won’t see a network request and instead it will resolved with your cached data. refetch is useful if you think your data might be stale and you’d like to refresh data from your server.

On top of that, the other difference would be the set of options each function can take. refetch is limited to variables, where the query function allows you to pass additional query options, such as context, or even a different query itself.

Hope this helps!

2 Likes

Fully understood. thanks!