r/reactjs • u/the_good_dev • 29d ago
Needs Help Catching problem with react query
Hey I am using tanstack react query I have one component which has
const { data, isPending, isFetching, refetch, isError } = useQuery({
queryKey: ["get"],
queryFn: () => axios.get("http://localhost:3000/"),
staleTime: 60 * 1000
})
On pressing a button i render component 2 with same query key within the catching time with query as
const { data, isPending, isFetching, refetch, isError } = useQuery({
queryKey: ["get"],
queryFn: () => axios.get("http://localhost:3000/"),
// no stale time here
})
Ideally it should not request the backend but it is requesting server
3
u/maksymkoval 29d ago
This is expected: staleTime belongs to each useQuery call, not to the cached data. The cache is shared by key, but every component decides on its own whether that data is stale.
Component 2 has no staleTime, so it uses the default of 0. For that component the cached data is already stale, and with refetchOnMount: true (also the default) it refetches in the background when it mounts. You should still see the cached data right away (isPending is false), with isFetching true while the request runs.
Two ways to fix it:
const getQuery = queryOptions({
queryKey: ["get"],
queryFn: () => axios.get("http://localhost:3000/"),
staleTime: 60 * 1000,
})
useQuery(getQuery)
2. Or set a default for the whole app:
new QueryClient({ defaultOptions: { queries: { staleTime: 60 * 1000 } },})
Option 1 is nicer anyway because the key and the fetcher live in one place.
3
u/Alarming_Ad_257 29d ago
staleTime is set per useQuery call, not per key. Your second component uses the default staleTime: 0, so when it mounts the cached data counts as stale for it, and refetchOnMount kicks in. Data in the cache doesn’t stop a refetch; staleTime is what does.
Either give both the same staleTime, or set it once in QueryClient defaultOptions. Even cleaner is pulling the query into a shared queryOptions() or custom hook, so both components use the exact same config.