author avatar

anujeet.swain

Mon Sep 30 2024

While using React-Query, Cache invalidation is key for keeping your data up-to-date with server state.
Data becomes "stale" after a set time (staleTime), and stale data gets re-fetched when the query is re-triggered (e.g., on component remount, on focus, or on manual refetch).

Following cache invalidation techniques are used to set the data as "stale" in react query:
• Implicitly setting up the staleTime .
• Adding triggers to react-query: refetchOnWindowFocus , refetchOnReconnect, refetchOnMount , refetchInterval .
• Manual invalidation for specific queries using queryClient.invalidateQueries() .
To have more control over specific query invalidation, we can utilise the queryKey property:


queryClient.invalidateQueries({
  queryKey: ['todos'],
})




queryClient.invalidateQueries({
  queryKey: ['todos', { type: 'done' }],
})


#react-query #cache-invalidation #data-synchronization