Middle
How to cache requests on the frontend and how to manage caching?
sobes.tech AI
Answer from AI
Caching requests on the frontend helps reduce server load and speed up data loading. Main methods:
- HTTP Caching: using Cache-Control, ETag, Last-Modified headers to manage caching at the browser and proxy level.
- In-memory caching: storing request results in variables or state (e.g., in React) for reuse without new requests.
- IndexedDB or localStorage: for long-term data storage between sessions.
Cache management includes:
- Setting cache lifetime (TTL).
- Invalidating cache when data changes (e.g., on event or version).
- Using libraries (e.g., React Query, SWR) that automate caching and data updating.
Example using fetch and simple in-memory cache:
const cache = new Map();
async function fetchWithCache(url) {
if (cache.has(url)) {
return cache.get(url);
}
const response = await fetch(url);
const data = await response.json();
cache.set(url, data);
return data;
}
This approach is simple but requires manual cache invalidation management.