T
TanStack•3y ago
correct-apricot

Will it fetch multiple time in this example ?

I have an endpoint that sends me a big object (ex: all posts + all messages). I'd like to fetch only once and compute only once derivated data. I'm thinking of creating multiple hooks:
const useAllPostsAndCommentsQuery = () => useQuery(
["posts"],
fetchAll
)

const useAllPostIdsQuery = () => useQuery(
["posts"],
fetchAll,
{select: posts => posts.map(p => p.id))}
)

const useAllCommentsQuery = () => useQuery(
["posts"],
fetchAll,
{select: posts => posts.flatMap(p => p.comment)}
)
const useAllPostsAndCommentsQuery = () => useQuery(
["posts"],
fetchAll
)

const useAllPostIdsQuery = () => useQuery(
["posts"],
fetchAll,
{select: posts => posts.map(p => p.id))}
)

const useAllCommentsQuery = () => useQuery(
["posts"],
fetchAll,
{select: posts => posts.flatMap(p => p.comment)}
)
Will it fetch multiple time or recompute the select function multiple times ?
6 Replies
foreign-sapphire
foreign-sapphire•3y ago
with the default staleTime of zero, it will do background refetches. set a staleTime to avoid it: https://tkdodo.eu/blog/react-query-as-a-state-manager
React Query as a State Manager
Everything you need to know to make React Query your single source of truth state manager for your async state
correct-apricot
correct-apricotOP•3y ago
Thanks 🙇 I'll give it a read The stale time makes sense, does that means react-query only checks the key? For example:
const useFirstQuery = useQuery(["sameKey"], fetchFn, {staleTime: 10000});

const useSecondQuery = useQuery(["sameKey"], differentFetchFn, {staleTime: 10000});
const useFirstQuery = useQuery(["sameKey"], fetchFn, {staleTime: 10000});

const useSecondQuery = useQuery(["sameKey"], differentFetchFn, {staleTime: 10000});
would only run fetchFn and not differentFetchFn
foreign-sapphire
foreign-sapphire•3y ago
queryKey and queryFn should be a pair that always go together. It's likely not right to have the same key with a different queryFn, as the key has to provide all dependencies for the queryFn
correct-apricot
correct-apricotOP•3y ago
Thanks that makes sense, I think we need in the end is to stick to a single useQuery, add a staleTime and memoïze derived data when it is computation expensive
other-emerald
other-emerald•3y ago
To be checked but the final memoization might not be needed if the data lie in RQ
foreign-sapphire
foreign-sapphire•3y ago
if you use select for deriving data, you don't need to memoize the result separately, but you need to memoize the select function itself t avoid it from running on each render: https://tkdodo.eu/blog/react-query-data-transformations#3-using-the-select-option
React Query Data Transformations
Learn the possibilities to perform the quite common and important task of transforming your data with react-query

Did you find this page helpful?