Skip to content
Advertisement

React-Query useQuery is caching response

I have following code

const { 
   isLoading, 
   error, 
   data: calculatorProducts 
} = useQuery('fetchSomething', ()=> fetchFunc())

This function should be called when I visit my main page, but when returning to this route from another page this request is not triggered and I don’t get fresh data. What I want is this query to be called every time like useEffect

Advertisement

Answer

data from the cache is always returned if there is data in the cache. Additionally, react-query will update stale queries in the background on certain occasions, e.g. when a component mounts. This technique is called stale-while-revalidate.

All queries are instantly stale per default, so if you go to a route from a different page, you should get data from the cache and still see a request in the devtools. If not, then maybe your component isn’t really mounting?

If you want data to be removed from the cache when all components that use this data unmount, you can set cacheTime: 0. But it means you’ll get a hard loading with a spinner when you come back, which is what react-query is trying to avoid

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement