@lindeneg/browser-cache
React hook for caching data in localStorage.
Installation
yarn add @lindeneg/browser-cache
Usage
import useBrowserCache from '@lindeneg/browser-cache';
type SomeCacheType = {
...
}
function SomeComponent() {
const { cache } = useBrowserCache<SomeCacheType>(config);
// set item
cache.set('id', 1);
// get item
cache.value('id');
// listen to event
cache.on('trim', (removed) => {
console.log('trim removed these keys from cache: ', removed);
});
// and so on
}
Or with React.Context
for a shared cache to be used by multiple components.
import {
BrowserCacheContextProvider,
useCacheContext,
} from '@lindeneg/browser-cache';
function ProviderComponent({ children }: { children: React.ReactNode }) {
return (
<BrowserCacheContextProvider config={config}>
{children}
</BrowserCacheContextProvider>
);
}
function ConsumerComponent() {
const { cache } = useCacheContext<SomeCacheType>();
// set item
cache.set('id', 1);
// and so on
return <div></div>;
}
The documentation here can be used.