Skip to content

About

A revolutionary React package that automatically prunes and re-hydrates inactive tabs to prevent memory bloat in long-lived web applications.

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Repository files navigation

react-tab-refresh — Automatic Memory & State Pruning for React

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 version Bundle Size React TypeScript Vitest License


NPM Package  •  Architecture  •  Core Features  •  API Reference  •  Report Bug  •  Request Feature


Table of Contents


The Problem & Solution

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:

  1. Serializes essential state cleanly to sessionStorage via StorageManager.
  2. Unmounts the heavy React subtree to release DOM nodes and heap memory.
  3. Re-hydrates and restores your component state seamlessly the moment the user returns.

Quick Start & Installation

Installation

npm install react-tab-refresh
# or
yarn add react-tab-refresh
# or
pnpm add react-tab-refresh

1. Wrap Your Application

import { PruneProvider } from "react-tab-refresh";

function App() {
  return (
    <PruneProvider config={{ pruneAfter: "30m" }}>
      <MainDashboard />
    </PruneProvider>
  );
}

2. Mark Essential State

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>
  );
}

Core Features & Capabilities

Intelligent Inactivity & Memory Pruning

  • 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 InactivityMonitor without interrupting active sessions.

Persistent Prunable State Hooks

  • usePrunableState: Drop-in useState replacement with custom serialization, validation, and TTL expiration.
  • Storage Helpers: Includes useClearPrunableState and useStorageUsage to audit or clear persisted keys on demand.

Lifecycle Cleanup & Rehydration

  • Graceful Teardown: Register cleanup callbacks (registerCleanup) to close WebSockets or cancel timers right before pruning.
  • Smooth Return UX: Display a custom placeholder skeleton during rehydration and trigger onRehydrate to reconnect live services.

API Reference

<PruneProvider>

<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

usePrunableState(key, initialValue, options?)

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(),
  }
);

usePruningState()

const {
  isPruned,
  isRehydrating,
  metrics,
  forceRehydrate,
  registerCleanup,
  unregisterCleanup,
} = usePruningState();

Advanced Usage & Troubleshooting

Custom Serialization (Dates, Maps, Sets)

const [timestamp, setTimestamp] = usePrunableState("timestamp", new Date(), {
  serialize: (date) => date.toISOString(),
  deserialize: (str) => new Date(str),
});

WebSocket Cleanup & Monitoring

const { registerCleanup, metrics, isPruned, forceRehydrate } = usePruningState();

useEffect(() => {
  const ws = new WebSocket("wss://api.example.com/chat");
  registerCleanup("websocket", () => ws.close());
  return () => ws.close();
}, [registerCleanup]);

Common Issues & Solutions

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

Running Tests

npm test              # Run Vitest unit suite
npm run test:coverage # Generate V8 coverage report

Engineering Highlights & Architecture

System Architecture Overview

react-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 |
+-------------------+           +-------------------+           +-------------------+

Browser Support & Capability Matrix

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.


Project Directory Structure

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

Developer Info & Socials

react-tab-refresh is created and maintained by:


License

This project is licensed under the MIT License.

Built with ❤️ to eliminate browser tab bloat in long-lived React apps

About

A revolutionary React package that automatically prunes and re-hydrates inactive tabs to prevent memory bloat in long-lived web applications.

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages