Stop the memory bloat — a lightweight React library that monitors tab inactivity, DOM node count, and heap usage to automatically serialize essential state, unmount heavy component trees, and re-hydrate seamlessly when users return.
NPM Package • Architecture • Core Features • API Reference • Report Bug • Request Feature
- Title & Value Proposition
- Tech Stack Badges
- Package & CTA Links
- The Problem & Solution
- Quick Start & Installation
- Core Features & Capabilities
- API Reference
- Advanced Usage & Troubleshooting
- Engineering Highlights & Architecture
- Project Directory Structure
- Developer Info & Socials
- License
Modern users keep web application tabs open for days or weeks. Over time, DOM nodes, event listeners, and JS heaps grow—leading to tab crashes, OS slowdowns, and stale background data.
When a tab becomes hidden and crosses your inactivity, memory, or DOM node thresholds, react-tab-refresh automatically:
- Serializes essential state cleanly to
sessionStorageviaStorageManager. - Unmounts the heavy React subtree to release DOM nodes and heap memory.
- Re-hydrates and restores your component state seamlessly the moment the user returns.
npm install react-tab-refresh
# or
yarn add react-tab-refresh
# or
pnpm add react-tab-refreshimport { PruneProvider } from "react-tab-refresh";
function App() {
return (
<PruneProvider config={{ pruneAfter: "30m" }}>
<MainDashboard />
</PruneProvider>
);
}Replace useState with usePrunableState for state that should survive tree unmounting:
import { usePrunableState } from "react-tab-refresh";
function SearchComponent() {
const [results, setResults] = usePrunableState("search_results", []);
const [query, setQuery] = usePrunableState("search_query", "");
return (
<div>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
{results.map((result) => (
<div key={result.id}>{result.title}</div>
))}
</div>
);
}- Multi-Signal Triggers: Prune based on tab inactivity duration (
'30m','1h','2d', or ms), DOM node count (maxDomNodes), or JS heap threshold (maxMemoryMb). - Page Visibility Aware: Tracks hidden tab transitions safely via
InactivityMonitorwithout interrupting active sessions.
usePrunableState: Drop-inuseStatereplacement with custom serialization, validation, and TTL expiration.- Storage Helpers: Includes
useClearPrunableStateanduseStorageUsageto audit or clear persisted keys on demand.
- Graceful Teardown: Register cleanup callbacks (
registerCleanup) to close WebSockets or cancel timers right before pruning. - Smooth Return UX: Display a custom
placeholderskeleton during rehydration and triggeronRehydrateto reconnect live services.
<PruneProvider
config={{
pruneAfter: "30m", // Time before pruning (default: '30m')
maxMemoryMb: 600, // Memory threshold in MB (Chrome/Edge)
enableMemoryMonitoring: false, // Enable memory-based pruning
maxDomNodes: 10000, // Max DOM nodes threshold
onPrune: () => {}, // Hook before pruning
onRehydrate: () => {}, // Hook after rehydration
debug: false, // Enable debug logs
}}
placeholder={<LoadingScreen />} // Shown while rehydrating
>
<App />
</PruneProvider>| Config Option | Type | Default | Description |
|---|---|---|---|
pruneAfter |
string | number |
'30m' |
Inactivity period before pruning ('30m', '1h', '2d', or ms) |
maxMemoryMb |
number |
undefined |
JS heap threshold in MB (Chrome/Edge only) |
enableMemoryMonitoring |
boolean |
false |
Enables performance.memory monitoring |
maxDomNodes |
number |
undefined |
DOM element count threshold before pruning |
onPrune |
() => void | Promise<void> |
undefined |
Callback executed prior to unmounting |
onRehydrate |
() => void | Promise<void> |
undefined |
Callback executed after rehydration |
debug |
boolean |
false |
Logs pruning lifecycle events |
| Parameter | Type | Description |
|---|---|---|
key |
string |
Unique storage identifier |
initialValue |
T |
Fallback initial state |
options |
PrunableStateOptions<T> |
Optional serialize, deserialize, validate, ttl, onExpired, debug |
const [user, setUser] = usePrunableState(
"current_user",
{ id: null, name: "" },
{
validate: (value) => value.id !== null,
ttl: 24 * 60 * 60 * 1000,
onExpired: () => fetchFreshUserData(),
}
);const {
isPruned,
isRehydrating,
metrics,
forceRehydrate,
registerCleanup,
unregisterCleanup,
} = usePruningState();const [timestamp, setTimestamp] = usePrunableState("timestamp", new Date(), {
serialize: (date) => date.toISOString(),
deserialize: (str) => new Date(str),
});const { registerCleanup, metrics, isPruned, forceRehydrate } = usePruningState();
useEffect(() => {
const ws = new WebSocket("wss://api.example.com/chat");
registerCleanup("websocket", () => ws.close());
return () => ws.close();
}, [registerCleanup]);| Issue | Cause | Solution |
|---|---|---|
| State Loss | Non-serializable functions or class instances | Persist serializable plain data or supply serialize/deserialize |
| Flicker on Return | Re-mounting large trees takes frames | Pass a skeleton element to <PruneProvider placeholder={...}> |
| WebSocket Drop | Unmounting disconnects live sockets | Use registerCleanup before prune and onRehydrate to reconnect |
| Quota Exceeded | sessionStorage 5–10MB browser cap |
Use useState for transient large arrays; persist only essential state |
npm test # Run Vitest unit suite
npm run test:coverage # Generate V8 coverage reportreact-tab-refresh pairs zero-dependency Rollup bundling (~8KB minified, ~3KB gzipped) with a decoupled monitor, storage adapter, and React context layer.
+-----------------------------------------------------------------------------------+
| React Application & PruneProvider |
| PruningContext | Children Tree | Rehydration Placeholder |
+-----------------------------------------------------------------------------------+
│
┌───────────────────────────────┼───────────────────────────────┐
▼ ▼ ▼
+-------------------+ +-------------------+ +-------------------+
| InactivityMonitor | | State Hooks | | StorageManager |
| Visibility API & | | usePrunableState | | Serializes State |
| Memory/DOM Checks | | usePruningState | | to sessionStorage |
+-------------------+ +-------------------+ +-------------------+
| Feature | Chrome | Firefox | Safari | Edge |
|---|---|---|---|---|
| Page Visibility API | ✅ | ✅ | ✅ | ✅ |
| SessionStorage Persistence | ✅ | ✅ | ✅ | ✅ |
| Heap Memory Monitoring | ✅ | ❌ | ❌ | ✅ |
Memory monitoring (performance.memory) is Chrome/Edge only and gracefully falls back to inactivity and DOM node pruning on other browsers.
react-tab-refresh-package/
├── examples/ # Basic and advanced React usage examples
├── src/ # Library TypeScript source
│ ├── __tests__/ # Vitest + Testing Library test suite
│ ├── components/ # PruneProvider tree lifecycle wrapper
│ │ └── PruneProvider.tsx
│ ├── context/ # PruningContext state & cleanup registry
│ │ └── PruningContext.tsx
│ ├── core/ # Inactivity, DOM & memory monitor
│ │ └── InactivityMonitor.ts
│ ├── hooks/ # React hooks for state and pruning metrics
│ │ ├── usePrunableState.ts
│ │ └── usePruningState.ts
│ ├── types/ # Public TypeScript definitions
│ │ └── index.ts
│ ├── utils/ # Storage adapter & helpers
│ │ ├── helpers.ts
│ │ └── StorageManager.ts
│ └── index.ts # Public library exports
├── LICENSE # MIT License
├── package.json # Package manifest, Rollup & Vitest scripts
├── README.md # Comprehensive documentation
├── rollup.config.js # ESM/CJS & dts bundle configuration
├── tsconfig.json # TypeScript compiler configuration
└── vitest.config.ts # Vitest test configuration
react-tab-refresh is created and maintained by:
- Md Shah Aman Patwary — Creator & Lead Software Engineer
- 🌐 GitHub: @TAIJULAMAN
- 💼 LinkedIn: shahamanpatwary
- 📧 Email: mdshahamanpatwary@gmail.com
This project is licensed under the MIT License.