Redux & Redux Toolkit
/Advanced
Cache Management
Definition
The system by which RTK Query temporarily stores the results of API requests in the Redux store to prevent redundant network requests and provide instant UI rendering.
Explain Like I'm New
If you visit the Homepage, it fetches 10 posts and saves them. If you click on an About page, and then click back to the Homepage, RTK Query says 'Wait! I already have those 10 posts!' It renders them instantly from memory instead of hitting the database again.
Real World Example
By default, RTK Query caches data for 60 seconds after the last component using that data unmounts. If you go back to the page within 60 seconds, it's instant.
Common Use Cases
- •Reducing server load
- •Instant UI navigation
Terminal Output
bash / terminal
/*
How the Cache Lifecycle Works:
1. Component A mounts and calls useGetUsersQuery().
2. RTK Query sees no cache. Makes network request. Returns Data.
3. Component B mounts and calls useGetUsersQuery().
4. RTK Query sees the cache! Instantly provides Data to B (No network request).
5. Component A and B unmount. Nobody is using the Data anymore.
6. A 60-second timer starts.
7. If 60 seconds pass, RTK Query deletes the Data from Redux to free up memory (Garbage Collection).
*/
Interview Questions
basic
- By default, how many seconds does RTK Query keep unused data in the cache before deleting it?
intermediate
- How does RTK Query know if two components are asking for the exact same data?