r/reactjs • • 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

0 Upvotes

4 comments sorted by

View all comments

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.