Cache results to speed up repeated queries.
Simple in-memory cache:
const cache = useRef(new Map());
const fetchWithCache = async (query) => {
if (cache.current.has(query)) {
return cache.current.get(query);
}
const results = await fetchSuggestions(query);
cache.current.set(query, results);
return results;
};
Cache considerations:
- Set maximum cache size (LRU eviction)
- Define TTL for freshness
- Clear cache on context change (user logs out)
Prefix matching: Results for "rea" may contain results for "react". Reuse when possible.