I want to create a custom hook that maintains a cache and fetches only new items.
Expected behavior:
If I requested [1, 2, 3, 4, 5] initially, it fetches all [1, 2, 3, 4, 5] since the cache is empty.
If I requested [1, 2, 3] then, it shouldn't fetch anything and returns from the cache.
If I requested [4, 5, 6] then, it should take 4 and 5 from the cache and fetch only 6 and add that to the cache.
How can I achieve this optimistically?
If you're already using react-query, then you don't need a custom hook: it already manages this cache for you based on your query keys:
At its core, React Query manages query caching for you based on query keys.
It also already provides a hook for parallel (concurrent), independent queries. That hook is called useQueries:
const results = useQueries({
queries: [
{ queryKey: ['post', 1], queryFn: () => fetchPost(1) },
{ queryKey: ['post', 2], queryFn: () => fetchPost(2) },
],
});