"use client"; import { useEffect, useRef, useState } from "react"; export type ResourceStatus = "loading" | "done" | "error"; export interface ResourceState { status: ResourceStatus; data?: T; error?: unknown; } const cache = new Map(); const inFlight = new Map>(); function cachedHit(key: string | null): T | undefined { if (key != null && cache.has(key)) return cache.get(key) as T; return undefined; } function dedupedFetch(key: string, fetcher: () => Promise): Promise { if (cache.has(key)) return Promise.resolve(cache.get(key) as T); const running = inFlight.get(key) as Promise | undefined; if (running) return running; const promise = fetcher() .then((data) => { cache.set(key, data); return data; }) .finally(() => { inFlight.delete(key); }); inFlight.set(key, promise); return promise; } /** * Loads a resource once per key, sharing the cache and in-flight requests * across all mounts. Reports the fetched (or cached) value through `onData` * so owners can hoist the result into their own state. */ export function useResource( key: string | null, fetcher: (() => Promise) | null, onData?: (data: T) => void ): ResourceState { const fetcherRef = useRef(fetcher); const onDataRef = useRef(onData); useEffect(() => { fetcherRef.current = fetcher; onDataRef.current = onData; }); const [state, setState] = useState>(() => { const hit = cachedHit(key); return hit !== undefined ? { status: "done", data: hit } : { status: "loading" }; }); const [prevKey, setPrevKey] = useState(key); if (key !== prevKey) { setPrevKey(key); const hit = cachedHit(key); setState(hit !== undefined ? { status: "done", data: hit } : { status: "loading" }); } useEffect(() => { if (!key || !fetcherRef.current) return; if (cache.has(key)) { onDataRef.current?.(cache.get(key) as T); return; } let cancelled = false; const run = fetcherRef.current; dedupedFetch(key, run) .then((data) => { if (cancelled) return; setState({ status: "done", data }); onDataRef.current?.(data); }) .catch((err) => { if (cancelled) return; setState({ status: "error", error: err }); }); return () => { cancelled = true; }; }, [key]); return state; }