react-redis-cache
v1.0.1
Published
A Redis-like cache for React with Redux integration, TTL, eviction policies, Pub/Sub, and async API caching
Maintainers
Readme
react-redis-cache
A Redis-like cache implementation for React with deep Redux integration, supporting TTL, eviction policies, data structures (Lists, Sets, Hashes), Pub/Sub, async API caching, persistence, and logging.
It works seamlessly across memory, localStorage, sessionStorage, and IndexedDB, making it a powerful choice for caching both UI state and API data in modern React applications.
Features
| Feature | Description |
|----------------------|-------------|
| TTL / Expiry | Set time-to-live for cached items. Expired items are auto-removed. |
| Eviction Policies| Supports LRU, LFU, and FIFO eviction when cache exceeds size limit. |
| Pause / Resume / Skip | Temporarily pause cache reads or skip next retrieval. |
| Pub/Sub | Subscribe to changes on cache keys or channels. |
| Data Structures | Lists, Sets, and Hashes, similar to Redis. |
| Async API Caching| getOrFetch automatically fetches & caches API results. |
| Redux Integration| Auto-cache Redux slices, update on specific actions. |
| Logging | Optional internal logging (enable/disable). |
| Persistence | Supports memory, localStorage, sessionStorage, and IndexedDB for reload persistence & large datasets. |
Installation
npm install react-redis-cacheUsage Example
import { ReactRedisCache } from "react-redis-cache";
import { store } from "./reduxStore";
const cache = new ReactRedisCache({
enableLogging: true,
evictionPolicy: "LRU",
mechanism: "indexedDB", // uses IndexedDB persistence
reduxConfig: {
store,
stateKey: "user",
actionsToWatch: ["UPDATE_USER", "LOGOUT"],
keyFn: (user) => `user:${user.id}`,
ttl: 60000 // 1 minute TTL
}
});
// Async get (IndexedDB returns Promise)
const cachedUser = await cache.get("user:123");
// Async API caching
const data = await cache.getOrFetch("posts", async () => {
const res = await fetch("/api/posts");
return await res.json();
}, 30000); // cache for 30s
// Pub/Sub
cache.subscribe("user:123", (updatedUser) =>
console.log("User updated", updatedUser)
);API Reference
Core Methods
- set(key, value, ttl?) → Promise
- get(key) → Promise
- del(key) → Promise
- flushall() → Promise
- flushByDate(date | number) → Promise
- pause() → void
- resume() → void
- skipNext(key) → void
Pub/Sub
- publish(channel, data) → void
- subscribe(channel, fn) → void
- unsubscribe(channel, fn?) → void
Data Structures
- Lists:
lpush,rpush,lpop,rpop,lrange - Sets:
sadd,srem,smembers - Hashes:
hset,hget,hgetall
Async API Caching
- getOrFetch(key, fetcher, ttl?) → Promise
Redux Integration
reduxConfig: {
store, // Redux store instance
stateKey: "user", // Slice key in state
actionsToWatch: ["UPDATE_USER"], // List of actions to trigger cache update
keyFn: (slice) => `user:${slice.id}`, // Cache key generator
ttl: 60000 // TTL in ms
}Persistence Mechanisms
| Mechanism | Description | |-----------------|-------------| | memory | In-memory cache. Cleared on reload. | | localStorage| Browser localStorage persistence. | | sessionStorage | Session-only persistence. | | indexedDB | Large dataset persistence across reloads. |
Notes
- IndexedDB operations are async →
getreturns a Promise. - Eviction policy triggers when cache exceeds 1000 entries (configurable).
- Logging is optional with
enableLogging: true. - TTL values are in milliseconds.
