25 lines
732 B
TypeScript
25 lines
732 B
TypeScript
import { useCallback, useMemo, useRef } from "react";
|
|
|
|
export function useWorkspaceTabCache<T>() {
|
|
const cacheRef = useRef(new Map<string, T>());
|
|
|
|
const getCached = useCallback((key: string) => cacheRef.current.get(key), []);
|
|
const setCached = useCallback((key: string, value: T) => {
|
|
cacheRef.current.set(key, value);
|
|
}, []);
|
|
const clearCached = useCallback((prefix?: string) => {
|
|
if (!prefix) {
|
|
cacheRef.current.clear();
|
|
return;
|
|
}
|
|
|
|
for (const key of Array.from(cacheRef.current.keys())) {
|
|
if (key.startsWith(prefix)) {
|
|
cacheRef.current.delete(key);
|
|
}
|
|
}
|
|
}, []);
|
|
|
|
return useMemo(() => ({ getCached, setCached, clearCached }), [getCached, setCached, clearCached]);
|
|
}
|