react-tab-refresh 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 [TAIJUL AMAN]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,362 @@
1
+ # react-tab-refresh
2
+
3
+ **Stop the Memory Bloat** — Automatically prune and re-hydrate your long-lived React apps to keep the browser fast.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/react-tab-refresh.svg)](https://www.npmjs.com/package/react-tab-refresh)
6
+ [![Bundle Size](https://img.shields.io/bundlephobia/minzip/react-tab-refresh)](https://bundlephobia.com/package/react-tab-refresh)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
8
+
9
+ ---
10
+
11
+ ## 📋 The Problem
12
+
13
+ In 2026, users keep tabs open for **weeks**. Even with optimized code, DOM nodes, event listeners, and JS heaps grow over time. This leads to:
14
+
15
+ - **Tab Crashing**: Browser kills the process due to high memory usage
16
+ - **System Slowdown**: Your app slows down the user's entire OS
17
+ - **Stale Data**: Background tabs show data from 3 days ago
18
+
19
+ ## ✨ The Solution
20
+
21
+ `react-tab-refresh` monitors your app's health. When a tab is hidden and exceeds memory limits or inactivity timers:
22
+
23
+ 1. **Serializes** your essential state to sessionStorage
24
+ 2. **Unmounts** the entire heavy React tree (freeing the heap)
25
+ 3. **Re-mounts** and restores everything instantly when the user returns
26
+
27
+ ---
28
+
29
+ ## 🚀 Quick Start
30
+
31
+ ### Installation
32
+
33
+ ```bash
34
+ npm install react-tab-refresh
35
+ # or
36
+ yarn add react-tab-refresh
37
+ # or
38
+ pnpm add react-tab-refresh
39
+ ```
40
+
41
+ ### 1. Wrap Your App
42
+
43
+ ```tsx
44
+ import { PruneProvider } from 'react-tab-refresh';
45
+
46
+ function App() {
47
+ return (
48
+ <PruneProvider config={{ pruneAfter: '30m' }}>
49
+ <MainDashboard />
50
+ </PruneProvider>
51
+ );
52
+ }
53
+ ```
54
+
55
+ ### 2. Mark "Essential" State
56
+
57
+ Replace `useState` with `usePrunableState` for data that must survive the pruning process.
58
+
59
+ ```tsx
60
+ import { usePrunableState } from 'react-tab-refresh';
61
+
62
+ function SearchComponent() {
63
+ // This state will be saved to sessionStorage before the component is unmounted
64
+ // and restored automatically upon return.
65
+ const [results, setResults] = usePrunableState('search_results', []);
66
+ const [query, setQuery] = usePrunableState('search_query', '');
67
+
68
+ return (
69
+ <div>
70
+ <input
71
+ value={query}
72
+ onChange={(e) => setQuery(e.target.value)}
73
+ placeholder="Search..."
74
+ />
75
+ {results.map((result) => (
76
+ <div key={result.id}>{result.title}</div>
77
+ ))}
78
+ </div>
79
+ );
80
+ }
81
+ ```
82
+
83
+ That's it! Your app will now automatically prune and rehydrate.
84
+
85
+ ---
86
+
87
+ ## 📚 API Reference
88
+
89
+ ### `<PruneProvider>`
90
+
91
+ The main provider component that wraps your app.
92
+
93
+ ```tsx
94
+ <PruneProvider
95
+ config={{
96
+ pruneAfter: '30m', // When to prune (default: 30 minutes)
97
+ maxMemoryMb: 600, // Memory threshold (Chrome only)
98
+ enableMemoryMonitoring: false, // Enable memory-based pruning
99
+ maxDomNodes: 10000, // DOM node threshold
100
+ onPrune: () => {}, // Callback before pruning
101
+ onRehydrate: () => {}, // Callback after rehydration
102
+ debug: false, // Enable debug logging
103
+ }}
104
+ placeholder={<LoadingScreen />} // Show during rehydration
105
+ >
106
+ <App />
107
+ </PruneProvider>
108
+ ```
109
+
110
+ #### Config Options
111
+
112
+ | Option | Type | Default | Description |
113
+ |--------|------|---------|-------------|
114
+ | `pruneAfter` | `string \| number` | `'30m'` | Inactivity time before pruning. Supports: `'30m'`, `'1h'`, `'2d'`, or milliseconds |
115
+ | `maxMemoryMb` | `number` | `undefined` | Memory threshold in MB (Chrome only) |
116
+ | `enableMemoryMonitoring` | `boolean` | `false` | Enable memory-based pruning |
117
+ | `maxDomNodes` | `number` | `undefined` | Maximum DOM nodes before pruning |
118
+ | `onPrune` | `() => void \| Promise<void>` | `undefined` | Callback before pruning (for cleanup) |
119
+ | `onRehydrate` | `() => void \| Promise<void>` | `undefined` | Callback after rehydration (for reconnection) |
120
+ | `debug` | `boolean` | `false` | Enable debug logging |
121
+
122
+ ### `usePrunableState()`
123
+
124
+ Drop-in replacement for `useState` with automatic persistence.
125
+
126
+ ```tsx
127
+ const [state, setState] = usePrunableState(key, initialValue, options);
128
+ ```
129
+
130
+ #### Parameters
131
+
132
+ | Parameter | Type | Description |
133
+ |-----------|------|-------------|
134
+ | `key` | `string` | Unique storage key |
135
+ | `initialValue` | `T` | Initial value (used if no stored value) |
136
+ | `options` | `PrunableStateOptions<T>` | Optional configuration |
137
+
138
+ #### Options
139
+
140
+ ```tsx
141
+ interface PrunableStateOptions<T> {
142
+ serialize?: (value: T) => string; // Custom serializer
143
+ deserialize?: (value: string) => T; // Custom deserializer
144
+ validate?: (value: T) => boolean; // Validate restored data
145
+ ttl?: number; // Time-to-live in ms
146
+ onExpired?: () => void; // Callback when data expires
147
+ debug?: boolean; // Enable debug logging
148
+ }
149
+ ```
150
+
151
+ #### Example with Options
152
+
153
+ ```tsx
154
+ const [user, setUser] = usePrunableState(
155
+ 'current_user',
156
+ { id: null, name: '' },
157
+ {
158
+ validate: (value) => value.id !== null,
159
+ ttl: 24 * 60 * 60 * 1000, // 24 hours
160
+ onExpired: () => fetchFreshUserData(),
161
+ }
162
+ );
163
+ ```
164
+
165
+ ### `usePruningState()`
166
+
167
+ Access pruning state and utilities.
168
+
169
+ ```tsx
170
+ const {
171
+ isPruned, // Whether app is currently pruned
172
+ isRehydrating, // Whether app is rehydrating
173
+ metrics, // Current metrics (inactiveMs, memoryMb, etc.)
174
+ forceRehydrate, // Force immediate rehydration
175
+ registerCleanup, // Register cleanup function
176
+ unregisterCleanup, // Unregister cleanup function
177
+ } = usePruningState();
178
+ ```
179
+
180
+ #### Example: WebSocket Cleanup
181
+
182
+ ```tsx
183
+ import { usePruningState } from 'react-tab-refresh';
184
+
185
+ function ChatComponent() {
186
+ const { registerCleanup } = usePruningState();
187
+
188
+ useEffect(() => {
189
+ const ws = new WebSocket('wss://api.example.com/chat');
190
+
191
+ // Register cleanup to close WebSocket before pruning
192
+ registerCleanup('websocket', () => {
193
+ ws.close();
194
+ });
195
+
196
+ return () => ws.close();
197
+ }, [registerCleanup]);
198
+
199
+ return <div>Chat UI</div>;
200
+ }
201
+ ```
202
+
203
+ ---
204
+
205
+ ## ⚠️ Common Issues & Solutions
206
+
207
+ ### Issue: State Loss
208
+
209
+ **Cause**: Non-serializable data (Functions, Classes) in state.
210
+
211
+ **Solution**: Use the `transform` option or avoid storing non-serializable data.
212
+
213
+ ```tsx
214
+ // ❌ Bad: Functions can't be serialized
215
+ const [handler, setHandler] = usePrunableState('handler', () => {});
216
+
217
+ // ✅ Good: Store serializable data only
218
+ const [config, setConfig] = usePrunableState('config', { url: '/api' });
219
+ ```
220
+
221
+ ### Issue: Flicker on Return
222
+
223
+ **Cause**: Re-mounting large trees takes time.
224
+
225
+ **Solution**: Use the `placeholder` prop to show a skeleton screen.
226
+
227
+ ```tsx
228
+ <PruneProvider
229
+ config={{ pruneAfter: '30m' }}
230
+ placeholder={<SkeletonScreen />}
231
+ >
232
+ <App />
233
+ </PruneProvider>
234
+ ```
235
+
236
+ ### Issue: WebSocket Drop
237
+
238
+ **Cause**: Unmounting closes active connections.
239
+
240
+ **Solution**: Use `registerCleanup` to gracefully close and `onRehydrate` to reconnect.
241
+
242
+ ```tsx
243
+ const { registerCleanup } = usePruningState();
244
+
245
+ useEffect(() => {
246
+ const ws = new WebSocket(url);
247
+
248
+ registerCleanup('websocket', () => {
249
+ ws.close();
250
+ });
251
+
252
+ return () => ws.close();
253
+ }, []);
254
+ ```
255
+
256
+ ### Issue: Quota Exceeded
257
+
258
+ **Cause**: SessionStorage has a 5-10MB limit.
259
+
260
+ **Solution**: Reduce state size or use selective persistence.
261
+
262
+ ```tsx
263
+ // Only persist essential data
264
+ const [largeData, setLargeData] = useState([]); // Not persisted
265
+ const [essentialData, setEssentialData] = usePrunableState('essential', {}); // Persisted
266
+ ```
267
+
268
+ ---
269
+
270
+ ## 🎯 Advanced Usage
271
+
272
+ ### Custom Serialization
273
+
274
+ For complex data types (Dates, Maps, Sets):
275
+
276
+ ```tsx
277
+ const [timestamp, setTimestamp] = usePrunableState(
278
+ 'timestamp',
279
+ new Date(),
280
+ {
281
+ serialize: (date) => date.toISOString(),
282
+ deserialize: (str) => new Date(str),
283
+ }
284
+ );
285
+ ```
286
+
287
+ ### Conditional Pruning
288
+
289
+ ```tsx
290
+ const { isPruned, forceRehydrate } = usePruningState();
291
+
292
+ if (isPruned && userClickedButton) {
293
+ forceRehydrate();
294
+ }
295
+ ```
296
+
297
+ ### Monitoring Metrics
298
+
299
+ ```tsx
300
+ const { metrics } = usePruningState();
301
+
302
+ console.log(`Inactive for: ${metrics.inactiveMs}ms`);
303
+ console.log(`Memory usage: ${metrics.memoryMb}MB`);
304
+ console.log(`DOM nodes: ${metrics.domNodes}`);
305
+ ```
306
+
307
+ ---
308
+
309
+ ## 🧪 Testing
310
+
311
+ The package includes comprehensive tests. Run them with:
312
+
313
+ ```bash
314
+ npm test
315
+ ```
316
+
317
+ For coverage:
318
+
319
+ ```bash
320
+ npm run test:coverage
321
+ ```
322
+
323
+ ---
324
+
325
+ ## 📦 Bundle Size
326
+
327
+ `react-tab-refresh` is designed to be lightweight:
328
+
329
+ - **Minified**: ~8KB
330
+ - **Gzipped**: ~3KB
331
+
332
+ ---
333
+
334
+ ## 🌐 Browser Support
335
+
336
+ | Feature | Chrome | Firefox | Safari | Edge |
337
+ |---------|--------|---------|--------|------|
338
+ | Page Visibility API | ✅ | ✅ | ✅ | ✅ |
339
+ | SessionStorage | ✅ | ✅ | ✅ | ✅ |
340
+ | Memory Monitoring | ✅ | ❌ | ❌ | ✅ |
341
+
342
+ **Note**: Memory monitoring (`performance.memory`) is Chrome/Edge only. The package gracefully degrades to time-based pruning on other browsers.
343
+
344
+ ---
345
+
346
+ ## 🤝 Contributing
347
+
348
+ Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md) for details.
349
+
350
+ ---
351
+
352
+ ## 📄 License
353
+
354
+ MIT © TAIJULAMAN
355
+
356
+ ---
357
+
358
+ ## 🙏 Acknowledgments
359
+
360
+ Inspired by the real-world problem of tab bloat in modern web applications. Built for the 2026 web where apps live in tabs for weeks.
361
+
362
+ ---
@@ -0,0 +1,2 @@
1
+ import '@testing-library/jest-dom';
2
+ //# sourceMappingURL=setup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"","sources":["../../src/__tests__/setup.ts"],"names":[],"mappings":"AAEA,OAAO,2BAA2B,CAAC"}
@@ -0,0 +1,3 @@
1
+ import type { PruneProviderProps } from '../types';
2
+ export declare function PruneProvider({ children, config, placeholder, }: PruneProviderProps): import("react/jsx-runtime").JSX.Element | null;
3
+ //# sourceMappingURL=PruneProvider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PruneProvider.d.ts","sourceRoot":"","sources":["../../src/components/PruneProvider.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAuC,MAAM,UAAU,CAAC;AAexF,wBAAgB,aAAa,CAAC,EAC1B,QAAQ,EACR,MAAW,EACX,WAAW,GACd,EAAE,kBAAkB,kDAuMpB"}
@@ -0,0 +1,3 @@
1
+ import type { PruningContextValue } from '../types';
2
+ export declare const PruningContext: import("react").Context<PruningContextValue | null>;
3
+ //# sourceMappingURL=PruningContext.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PruningContext.d.ts","sourceRoot":"","sources":["../../src/context/PruningContext.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAKpD,eAAO,MAAM,cAAc,qDAAkD,CAAC"}
@@ -0,0 +1,26 @@
1
+ import type { MonitorConfig, MonitorEvent, MonitorCallback, PruningMetrics } from '../types';
2
+ export declare class InactivityMonitor {
3
+ private config;
4
+ private logger;
5
+ private listeners;
6
+ private intervalId;
7
+ private hiddenAt;
8
+ private isRunning;
9
+ constructor(config: Partial<MonitorConfig>);
10
+ start(): void;
11
+ stop(): void;
12
+ on(event: MonitorEvent, callback: MonitorCallback): void;
13
+ off(event: MonitorEvent, callback: MonitorCallback): void;
14
+ getCurrentMetrics(): PruningMetrics;
15
+ private checkThresholds;
16
+ private emit;
17
+ private setupVisibilityListener;
18
+ private removeVisibilityListener;
19
+ private handleVisibilityChange;
20
+ private getInactiveTime;
21
+ private startPolling;
22
+ private stopPolling;
23
+ updateConfig(config: Partial<MonitorConfig>): void;
24
+ reset(): void;
25
+ }
26
+ //# sourceMappingURL=InactivityMonitor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InactivityMonitor.d.ts","sourceRoot":"","sources":["../../src/core/InactivityMonitor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACR,aAAa,EACb,YAAY,EACZ,eAAe,EACf,cAAc,EACjB,MAAM,UAAU,CAAC;AAalB,qBAAa,iBAAiB;IAC1B,OAAO,CAAC,MAAM,CAAgB;IAC9B,OAAO,CAAC,MAAM,CAAkC;IAChD,OAAO,CAAC,SAAS,CAAsD;IACvE,OAAO,CAAC,UAAU,CAA+C;IACjE,OAAO,CAAC,QAAQ,CAAuB;IACvC,OAAO,CAAC,SAAS,CAAS;gBAEd,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC;IAsB1C,KAAK,IAAI,IAAI;IAyBb,IAAI,IAAI,IAAI;IAeZ,EAAE,CAAC,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,eAAe,GAAG,IAAI;IAUxD,GAAG,CAAC,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,eAAe,GAAG,IAAI;IAUzD,iBAAiB,IAAI,cAAc;IAiBnC,OAAO,CAAC,eAAe;IAkDvB,OAAO,CAAC,IAAI;IAgBZ,OAAO,CAAC,uBAAuB;IAO/B,OAAO,CAAC,wBAAwB;IAUhC,OAAO,CAAC,sBAAsB,CAU5B;IAKF,OAAO,CAAC,eAAe;IAUvB,OAAO,CAAC,YAAY;IAepB,OAAO,CAAC,WAAW;IAUnB,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI;IAQlD,KAAK,IAAI,IAAI;CAIhB"}
@@ -0,0 +1,5 @@
1
+ import type { PrunableStateOptions } from '../types';
2
+ export declare function usePrunableState<T>(key: string, initialValue: T, options?: PrunableStateOptions<T>): [T, (value: T | ((prev: T) => T)) => void];
3
+ export declare function useClearPrunableState(): (key: string) => void;
4
+ export declare function useStorageUsage(): import("../types").StorageUsage;
5
+ //# sourceMappingURL=usePrunableState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePrunableState.d.ts","sourceRoot":"","sources":["../../src/hooks/usePrunableState.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAQrD,wBAAgB,gBAAgB,CAAC,CAAC,EAC9B,GAAG,EAAE,MAAM,EACX,YAAY,EAAE,CAAC,EACf,OAAO,GAAE,oBAAoB,CAAC,CAAC,CAAM,GACtC,CAAC,CAAC,EAAE,CAAC,KAAK,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAK,IAAI,CAAC,CA4G5C;AAKD,wBAAgB,qBAAqB,UAIvB,MAAM,UAKnB;AAKD,wBAAgB,eAAe,oCAa9B"}
@@ -0,0 +1,3 @@
1
+ import type { PruningContextValue } from '../types';
2
+ export declare function usePruningState(): PruningContextValue;
3
+ //# sourceMappingURL=usePruningState.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usePruningState.d.ts","sourceRoot":"","sources":["../../src/hooks/usePruningState.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,UAAU,CAAC;AAEpD,wBAAgB,eAAe,IAAI,mBAAmB,CAerD"}
@@ -0,0 +1,7 @@
1
+ export { PruneProvider } from './components/PruneProvider';
2
+ export { usePrunableState, useClearPrunableState, useStorageUsage } from './hooks/usePrunableState';
3
+ export { usePruningState } from './hooks/usePruningState';
4
+ export type { PrunableStateOptions, PruneProviderConfig, PruneProviderProps, PruningContextValue, PruningMetrics, StorageAdapter, StorageUsage, } from './types';
5
+ export { createStorageAdapter } from './utils/StorageManager';
6
+ export { InactivityMonitor } from './core/InactivityMonitor';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAG3D,OAAO,EAAE,gBAAgB,EAAE,qBAAqB,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AACpG,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAG1D,YAAY,EACR,oBAAoB,EACpB,mBAAmB,EACnB,kBAAkB,EAClB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,YAAY,GACf,MAAM,SAAS,CAAC;AAGjB,OAAO,EAAE,oBAAoB,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC"}