Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

114
Views
How to persist the same data even after useQuery key change and component is unmounted & remounted again

I have been stuck with one issue, let's say I have this below custom react query hook.

export const useGetData = () => {
  const { filter } = useSelector((state) => state.filterReducer);

  const queryInfo = useQuery(["filter", filter], () => getData(), {
    staleTime: Infinity,
    cacheTime: Infinity,
    enabled: false,
    keepPreviousData: true
  });

  return {
    ...queryInfo,
    data: useMemo(() => queryInfo.data, [queryInfo.data])
  };
};

so here I'm actually storing the user's filter state in the global redux store and whenever the user makes any changes this will create a new cache with data as undefined. so since this query has been set enabled to false it will not make an API call and the user has to manually click on the apply filter button in the UI in order to get the data, which actually makes refetch call and gets the data update the existing undefined cache with the data returned from the server.

since this query has keepPreviousData set to true it will keep the previous data in the UI. but in the cache, the new filter has been updated with undefined. So now let's say the user doesn't apply the filter (by clicking on the apply filter button), they just change the filter (which actually creates a new cache), and let's say the user unmounts the component and mounts the component again (using a toggle), the previous data which was showing has gone! (because now it's showing undefined)

Is it possible to keep the previous data if enabled: false, keepPreviousData: true, even if the component is unmounted and mounted back again?

here is the reproduced code sandbox - link

I'm stuck with this issue for the past couple of days not sure how to fix it. Any help on this will be highly appreciated thanks in advance.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!