useMemo and queryFn
So I have a fairly simple query function, shown below. I was wondering if
const body = await response.json() and zResponse.parse(body); would run on every render? Would it make sense to wrap them in a useMemo with response as the dependency? This queryFn is in a custom hook.
3 Replies
manual-pink•3y ago
the queryFunction itself does not run on every render, only when a fetch or refetch should be made
foreign-sapphireOP•3y ago
Ah yes, that makes sense. Just actually stumbled across your blog post about this, i guess if I was doing some transformations in the actual useQuery part of the hook then it might make sense to use useMemo. Thanks!
rare-sapphire•3y ago
I agree entirely with Dominik, but to be exhaustive you couldn't use useMemo inside of a query function. You can't call React hooks from within a function defined in a component; only at the top level of a function component or hook.
Dominik has written (excellently, as always) about approaches for data transformation and their associated tradeoffs here:
https://tkdodo.eu/blog/react-query-data-transformations