Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

120
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda