useFetch with in-memory cache

Custom Hooks — Advanced React challenge.

Build a useFetch hook with a shared, module-level in-memory cache. Repeated requests for the same URL — whether from a remount or from a second component mounted at the same moment — must reuse cached data or an in-flight request instead of firing a duplicate fetch. The hook must also be resilient to callers passing a new fetcher function reference on every render.

Requirements

Signature

function useFetch(url: string, fetcher: (url: string) => Promise<any>): {
  data: any;
  loading: boolean;
  error: Error | null;
}
function resetFetchCache(): void
function getStatusClassName(state: { loading: boolean; error: Error | null }): string

Example

const { data, loading, error } = useFetch("/api/user/1", fetchUser);
// two components calling useFetch("/api/user/1", fetchUser) at the same
// time only ever trigger ONE real call to fetchUser
// re-rendering with a brand-new fetcher reference for the same url
// must NOT trigger another fetch

Constraints

🏷️ Get 20% OFF on Yearly & Lifetime plans — use code 🏷️ Get 20% OFF on Yearly & Lifetime plans — use code 🏷️ Get 20% OFF on Yearly & Lifetime plans — use code 🏷️ Get 20% OFF on Yearly & Lifetime plans — use code 🏷️ Get 20% OFF on Yearly & Lifetime plans — use code 🏷️ Get 20% OFF on Yearly & Lifetime plans — use code
Loading workspace…