shelving
Version:
Toolkit for using data in JavaScript.
22 lines (21 loc) • 965 B
JavaScript
import { createContext, createElement, useContext, useRef } from "react";
import { UnexpectedError } from "../error/UnexpectedError.js";
/**
* Create a cache context that can be provided to React elements and allows them to call `useCache()`
* - Cache is a `Map` indexed by strings that can be used to store any value.
*/
export function createCacheContext() {
const context = createContext(undefined);
const useCache = () => {
const cache = useContext(context);
if (!cache)
throw new UnexpectedError("useCache() must be used inside <Cache>", { caller: useCache });
return cache;
};
const CacheContext = ({ children }) => {
// biome-ignore lint/suspicious/noAssignInExpressions: This is the most efficient way to do this.
const cache = (useRef().current ||= new Map());
return createElement(context.Provider, { children, value: cache });
};
return { useCache, CacheContext };
}