Prevent query re-fetching on component remount #616
Replies: 7 comments 20 replies
-
Please post a codesandbox or some code please. To help effectively, you should alway submit something more than a description :) |
Beta Was this translation helpful? Give feedback.
-
Hello gentlemen, I would like to present you my solution for the query refetching on re-mount. I guess that everytime the component remounts, the queryKey is regenerated, therefore leading to useQuery being constantly re-updated even though its value is the same. What worked for me as a workaround is passing the queryKey from a parent component's state. This way, I can navigate through my app while useQuery refteches only when the "globalState.text" is changed. To sum up:
`
|
Beta Was this translation helpful? Give feedback.
-
Anyone coming back to this with similar issue: My |
Beta Was this translation helpful? Give feedback.
-
Just giving my two cents. I'v got myself on this anoing behavior. Every tab clicked making react-query fetch again.
useRef ensure it runs only on the browser |
Beta Was this translation helpful? Give feedback.
-
just found the solution for the exact same problem. it's on its query options check if data is equal between old and new data then set
|
Beta Was this translation helpful? Give feedback.
-
For anyone else that still encounters this issue. A version of the |
Beta Was this translation helpful? Give feedback.
-
My solution to this problem is to check if data is already in cache using export const useData = (searchParams: TSearchParams) => {
const queryClient = useQueryClient()
return useQuery<TDataResult[]>({
queryKey: ['searchResults', searchParams],
queryFn: () => getData(searchParams, queryClient),
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
staleTime: Infinity,
gcTime: Infinity,
})
} export const getData = async (searchParams: TSearchParams, queryClient: QueryClient) => {
const url = "some url"
// If search results are in cache, return them to prevent a refetch
const cachedData = queryClient.getQueryData(['searchResults', searchParams])
if (cachedData) {
return cachedData
}
return fetch(url)
.then(res => res.json())
.then(res => {
return res.results
})
.catch((error) => {
throw ('Error: ' + error)
})
} That way data is fetched only once. If a component is unmounted and mounted again, the service returns data from cache and doesn't make a refetch. Keep in mind that queryKey must be exactly the same to achieve this result. |
Beta Was this translation helpful? Give feedback.
-
Hi,
I was hoping someone could help me with the following issue: I have an inactive query, which is a part of an unmounted component (that was previously mounted). Then, once the component is remounted the query is re-fetched, rather than being taken from the cache. Is there any way to prevent this from happening?
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions