react-browser-cache
v1.0.1
Published
Production-ready hook-based browser caching system for React with TTL, stale-while-revalidate, and cross-tab sync.
Maintainers
Readme
react-browser-cache
A production-ready, hook-based browser caching system for React with TTL, stale-while-revalidate, and cross-tab synchronization.
🚀 Features
- Multi-Storage Support: localStorage, sessionStorage, IndexedDB, and Memory.
- TTL & Expiration: Automatic cache invalidation based on time-to-live.
- Stale-While-Revalidate: Return cached data immediately while fetching fresh data in the background.
- Cross-Tab Sync: Real-time synchronization across browser tabs using
BroadcastChannel. - TypeScript First: Fully type-safe API.
- Lightweight: Zero heavy dependencies, optimized for bundle size.
- JSON Safe: Built-in support for
Dateobjects in serialization.
📦 Installation
npm install react-browser-cache🛠️ Usage
1. Wrap your app with BrowserCacheProvider
import { BrowserCacheProvider } from 'react-browser-cache';
function App() {
return (
<BrowserCacheProvider config={{ defaultStorage: 'local', defaultTTL: 1000 * 60 * 5 }}>
<MyComponent />
</BrowserCacheProvider>
);
}2. Use useBrowserCache for async data
import { useBrowserCache } from 'react-browser-cache';
const fetchUser = async () => {
const resp = await fetch('/api/user');
return resp.json();
};
function MyComponent() {
const { data, isLoading, error, refresh } = useBrowserCache({
key: 'user_profile',
fetcher: fetchUser,
storage: 'indexeddb',
ttl: 1000 * 60 * 60, // 1 hour
staleWhileRevalidate: true
});
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data.name}</h1>
<button onClick={() => refresh()}>Refresh</button>
</div>
);
}3. Use useCacheState for persistent state
import { useCacheState } from 'react-browser-cache';
function Counter() {
const [count, setCount] = useCacheState('counter_key', 0, { storage: 'local' });
return (
<button onClick={() => setCount(c => c + 1)}>
Count is {count}
</button>
);
}4. Read-only access with useCacheValue
const value = useCacheValue('my_key');5. Manual Invalidation
const { invalidate, clearAll } = useCacheInvalidate();
// Invalidate specific key
invalidate('user_profile');
// Clear entire storage
clearAll('indexeddb');📖 API Reference
BrowserCacheProvider Props
| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| config | GlobalCacheConfig | - | Global configuration for the cache. |
useBrowserCache Options
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| key | string | Required | Unique key for the cache entry. |
| fetcher | () => Promise<T> | Required | Async function to fetch data. |
| storage | StorageType | 'memory' | Storage adapter to use. |
| ttl | number | 300000 | Time to live in milliseconds. |
| staleWhileRevalidate | boolean | false | Fallback to stale data while revalidating. |
| syncTabs | boolean | true | Sync updates across tabs. |
🤝 Comparison with SWR/React Query
While SWR and React Query are excellent for server state, react-browser-cache focuses specifically on browser storage abstraction.
- Persistence: Unlike SWR which is primarily in-memory, this library is built to live in
localStorageorIndexedDB. - Offline First: Optimized for scenarios where you want data to persist across sessions and survive page reloads naturally.
- Cross-Tab Sync: Native support for keeping state in sync across multiple open tabs.
📄 License
MIT © Kloudz Computing
