Garbage Collection Time in React Query 2025

Garbage Collection Time in React Query 2025

Jab koi query React Query mein inactive ho jaati hai, to uska data memory mein limited time tak rehta hai. Uske baad React Query us data ko "Garbage Collection" ke through hata deta hai taaki memory efficient rahe.

1. Default Garbage Collection Time

Default cacheTime hota hai: 5 minutes (300000 ms)

// Query automatically removed from cache after 5 minutes of inactivity
useQuery({
  queryKey: ['todos'],
  queryFn: fetchTodos
});

2. Custom Garbage Collection Time (cacheTime)

Aap cacheTime ko customize kar sakte ho:

useQuery({
  queryKey: ['users'],
  queryFn: fetchUsers,
  cacheTime: 1000 * 60 * 10 // 10 minutes
});

3. Difference between cacheTime and staleTime

  • cacheTime: Query inactive hone ke baad kitni der tak memory mein rahe.
  • staleTime: Kitni der tak data ko fresh maana jaye (refetch nahi karega).

4. Set cacheTime to Infinity

Agar aap chahte ho ki query data kabhi delete na ho to:

useQuery({
  queryKey: ['products'],
  queryFn: fetchProducts,
  cacheTime: Infinity
});

5. Summary

  • cacheTime handles garbage collection.
  • Default: 5 minutes.
  • Can be customized as per use case.