T
TanStack3y ago
foreign-sapphire

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.
const queryFunction = async ({ numDocumento, numPoliza, first }: TRequest): Promise<TResponse> => {
const response = await fetch('http://someUrl.com/endpoint1/', {
method: 'POST',
body: JSON.stringify(
zRequest.parse({
numPoliza,
numDocumento,
first,
})
),
});

if (!response.ok) {
throw new Error('Response was not ok');
}

const body = await response.json();

zResponse.parse(body);

return body;
const queryFunction = async ({ numDocumento, numPoliza, first }: TRequest): Promise<TResponse> => {
const response = await fetch('http://someUrl.com/endpoint1/', {
method: 'POST',
body: JSON.stringify(
zRequest.parse({
numPoliza,
numDocumento,
first,
})
),
});

if (!response.ok) {
throw new Error('Response was not ok');
}

const body = await response.json();

zResponse.parse(body);

return body;
3 Replies
manual-pink
manual-pink3y ago
the queryFunction itself does not run on every render, only when a fetch or refetch should be made
foreign-sapphire
foreign-sapphireOP3y 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
rare-sapphire3y 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

Did you find this page helpful?