@biglogic/rgs 3.8.4 → 3.9.1

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/docs/README.md DELETED
@@ -1,483 +0,0 @@
1
- # 🚀 ARGIS (RGS) - Reactive Global State
2
-
3
- <div align="center">
4
-
5
- > **"Atomic Precision. Immutable Safety. Zen Simplicity."**
6
- > The state management engine that **won't let you fail**.
7
-
8
- [![npm version](https://img.shields.io/npm/v/@biglogic/rgs.svg)](https://npmjs.org/package/@biglogic/rgs)
9
- [![npm downloads](https://img.shields.io/npm/dm/@biglogic/rgs.svg)](https://npmjs.org/package/@biglogic/rgs)
10
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
11
- [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/)
12
- [![React](https://img.shields.io/badge/React-19+-61DAFB.svg)](https://react.dev/)
13
-
14
- </div>
15
-
16
- ---
17
-
18
- ## ⚡ TL;DR - Why ARGIS (RGS) Will Change How You Code Forever
19
-
20
- ```tsx
21
- // One line. Zero boilerplate. Enterprise-grade power.
22
- const useUser = gstate({
23
- name: 'Alice',
24
- cart: [],
25
- preferences: { theme: 'dark' }
26
- })
27
-
28
- // That's it. Use it anywhere:
29
- const name = useUser(s => s.name)
30
- const theme = useUser(s => s.preferences.theme)
31
-
32
- // Mutations? Just write it. Immer handles immutability automatically.
33
- useUser(s => {
34
- s.cart.push({ id: 1, item: 'Coffee Machine', price: 99 })
35
- })
36
- ```
37
-
38
- **Stop fighting your state management. Start building.**
39
-
40
- ---
41
-
42
- ## 🎯 Why Developers Are **Obsessed** With ARGIS (RGS)
43
-
44
- | Feature | Other Libraries | ARGIS (RGS) |
45
- |---------|----------------|--------------|
46
- | **API Complexity** | 10+ functions, providers, reducers | **1 function** - `gstate()` |
47
- | **Immutability** | Manual spreads, Redux boilerplate | **Automatic** - Powered by Immer |
48
- | **Security** | None | **AES-256 + RBAC + GDPR** built-in |
49
- | **Persistence** | Manual localStorage/sessionStorage | **First-class** - Auto-save anywhere |
50
- | **Offline/Cloud Sync** | Non-existent | **Local-First + Cloud Sync** included |
51
- | **Bundle Size** | 10-50KB+ | **~2KB** minimal / **~32KB** full |
52
- | **Type Safety** | Partial | **100% TypeScript** out of the box |
53
-
54
- ### 🔥 The Truth About State Management
55
-
56
- Most libraries make you **choose** between:
57
- - ✗ Simplicity vs Power
58
- - ✗ Security vs Speed
59
- - ✗ Offline vs Cloud
60
-
61
- **ARGIS (RGS) gives you ALL of it.**
62
-
63
- ---
64
-
65
- ## 🏆 RGS vs The Competition
66
-
67
- | Feature | **RGS (Argis)** | Zustand | Redux Toolkit | Recoil | Jotai |
68
- |---------|:---:|:---:|:---:|:---:|:---:|
69
- | **Philosophy** | Zen State | Minimalist | Enterprise Flux | Atomic | Atomic |
70
- | **API Surface** | **1 Function** | Simple | Complex | Complex | Simple |
71
- | **Mutations** | **Magic (Immer)** | Manual | Magic | Manual | Manual |
72
- | **Security** | 🛡️ **AES-256 + RBAC** | ❌ | ❌ | ❌ | ❌ |
73
- | **Persistence** | 💾 **First-class** | 🔌 | 🔌 | 🔌 | 🔌 |
74
- | **Local-First Sync** | ✅ **Built-in** | ❌ | ❌ | ❌ | ❌ |
75
- | **Bundle Size** | **~2KB/32KB** | ~1KB | >10KB | >20KB | ~3KB |
76
-
77
- > **RGS is the ONLY library treating Security and Persistence as first-class citizens.**
78
-
79
- ---
80
-
81
- ## 🚀 Installation
82
-
83
- ```bash
84
- # The fastest way to upgrade your React app
85
- npm install @biglogic/rgs
86
- ```
87
-
88
- ```bash
89
- # Or with pnpm
90
- pnpm add @biglogic/rgs
91
-
92
- # Or with yarn
93
- yarn add @biglogic/rgs
94
- ```
95
-
96
- ---
97
-
98
- ## 🎮 Quick Start - 30 Seconds to Glory
99
-
100
- ### The Zen Way (Recommended)
101
-
102
- ```tsx
103
- import { gstate } from '@biglogic/rgs'
104
-
105
- // ONE line creates a typed store hook
106
- const useStore = gstate({
107
- count: 0,
108
- user: { name: 'Alice', email: 'alice@example.com' }
109
- })
110
-
111
- function Counter() {
112
- // Type-safe selectors - the React way
113
- const count = useStore(s => s.count)
114
- const userName = useStore(s => s.user.name)
115
-
116
- // Direct mutations - just write JavaScript
117
- const increment = () => useStore(s => { s.count++ })
118
-
119
- return (
120
- <div>
121
- <h1>Hello, {userName}!</h1>
122
- <p>Count: {count}</p>
123
- <button onClick={increment}>+1</button>
124
- </div>
125
- )
126
- }
127
- ```
128
-
129
- ### The Classic Way (Global Store)
130
-
131
- ```tsx
132
- import { initState, useStore } from '@biglogic/rgs'
133
-
134
- // Initialize once at app root
135
- initState({ namespace: 'myapp' })
136
-
137
- // Use anywhere in your app
138
- const [user, setUser] = useStore('user')
139
- const [theme, setTheme] = useStore('theme')
140
- ```
141
-
142
- ---
143
-
144
- ## 🛡️ Enterprise-Grade Security (No Extra Code)
145
-
146
- ### AES-256-GCM Encryption
147
-
148
- ```tsx
149
- // Your sensitive data is encrypted automatically
150
- const useAuth = gstate({
151
- token: 'jwt-token-here',
152
- refreshToken: 'refresh-token'
153
- }, { encoded: true }) // 🔐 AES-256-GCM encryption enabled
154
- ```
155
-
156
- ### RBAC (Role-Based Access Control)
157
-
158
- ```tsx
159
- const store = gstate({
160
- adminPanel: { users: [], settings: {} },
161
- userProfile: {}
162
- }, {
163
- rbac: {
164
- admin: ['adminPanel', 'userProfile'],
165
- user: ['userProfile'],
166
- guest: []
167
- }
168
- })
169
-
170
- // Only admins can touch adminPanel
171
- store.set('adminPanel', { users: ['new'] }) // ✅ Works for admins
172
- ```
173
-
174
- ### GDPR Compliance
175
-
176
- ```tsx
177
- // Export all user data (GDPR requirement)
178
- store.exportData() // Returns JSON of all stored data
179
-
180
- // Delete all user data (GDPR "right to be forgotten")
181
- store.deleteData()
182
- ```
183
-
184
- ---
185
-
186
- ## 💾 Persistence That Just Works
187
-
188
- ### Built-in Storage Adapters
189
-
190
- ```tsx
191
- // localStorage (default) - survives browser restart
192
- const useSettings = gstate({ theme: 'dark' }, { persist: true })
193
-
194
- // sessionStorage - survives page refresh but not tab close
195
- const useSession = gstate({ temporary: 'data' }, { storage: 'session' })
196
-
197
- // Memory only - for ephemeral data
198
- const useMemory = gstate({ cache: [] }, { storage: 'memory' })
199
-
200
- // IndexedDB - for GB-scale data
201
- const useBigData = gstate({ dataset: [] })
202
- store._addPlugin(indexedDBPlugin({ dbName: 'my-app-db' }))
203
- ```
204
-
205
- ---
206
-
207
- ## 🔌 Plugins Ecosystem - Extend Without Limits
208
-
209
- RGS comes with **11+ official plugins** ready to supercharge your app:
210
-
211
- | Plugin | Purpose | One-Liner |
212
- |--------|---------|-----------|
213
- | `undoRedoPlugin` | Time travel through state | `store.undo()` / `store.redo()` |
214
- | `syncPlugin` | Cross-tab sync (no server) | `store._addPlugin(syncPlugin(...))` |
215
- | `indexedDBPlugin` | GB-scale storage | `store._addPlugin(indexedDBPlugin(...))` |
216
- | `cloudSyncPlugin` | Cloud backup & sync | `store.plugins.cloudSync.sync()` |
217
- | `devToolsPlugin` | Redux DevTools | `store._addPlugin(devToolsPlugin(...))` |
218
- | `immerPlugin` | Mutable-style updates | `store.setWithProduce('key', fn)` |
219
- | `snapshotPlugin` | Save/restore checkpoints | `store.takeSnapshot('backup')` |
220
- | `schemaPlugin` | Runtime validation | `store._addPlugin(schemaPlugin(...))` |
221
- | `guardPlugin` | Transform on set | `store._addPlugin(guardPlugin(...))` |
222
- | `analyticsPlugin` | Track changes | `store._addPlugin(analyticsPlugin(...))` |
223
- | `debugPlugin` | Console access (DEV) | `window.gstate.list()` |
224
-
225
- ### Undo/Redo - Never Lose Work
226
-
227
- ```tsx
228
- import { undoRedoPlugin } from '@biglogic/rgs'
229
-
230
- const store = gstate({ text: '' })
231
- store._addPlugin(undoRedoPlugin({ limit: 50 }))
232
-
233
- // User makes changes...
234
- store.set('text', 'Hello World')
235
- store.set('text', 'Hello Universe')
236
-
237
- // Oops! Let's go back
238
- store.undo() // Returns to 'Hello World'
239
- store.redo() // Returns to 'Hello Universe'
240
- ```
241
-
242
- ### Cross-Tab Sync - Real-Time Everywhere
243
-
244
- ```tsx
245
- import { syncPlugin } from '@biglogic/rgs/advanced'
246
-
247
- const store = gstate({ theme: 'light' })
248
- store._addPlugin(syncPlugin({ channelName: 'my-app' }))
249
-
250
- // Change in Tab 1 → Instantly updates Tab 2, Tab 3, etc.
251
- // ZERO server calls. Pure browser magic.
252
- ```
253
-
254
- ### Cloud Sync - Your Data, Everywhere
255
-
256
- ```tsx
257
- import { cloudSyncPlugin, createMongoAdapter } from '@biglogic/rgs/advanced'
258
-
259
- const adapter = createMongoAdapter(
260
- 'https://data.mongodb-api.com/...',
261
- 'your-api-key'
262
- )
263
-
264
- const store = gstate({ todos: [] })
265
- store._addPlugin(cloudSyncPlugin({
266
- adapter,
267
- autoSyncInterval: 30000 // Every 30 seconds
268
- }))
269
-
270
- // Manual sync when needed
271
- await store.plugins.cloudSync.sync()
272
- ```
273
-
274
- ---
275
-
276
- ## ☁️ Local-First Sync - Offline by Default
277
-
278
- The **killer feature** that makes RGS unique:
279
-
280
- ```tsx
281
- import { gstate, useSyncedState } from '@biglogic/rgs'
282
-
283
- // Create store with automatic offline-first sync
284
- const store = gstate({
285
- todos: [],
286
- user: null
287
- }, {
288
- namespace: 'myapp',
289
- sync: {
290
- endpoint: 'https://api.example.com/sync',
291
- authToken: () => localStorage.getItem('auth_token'),
292
- autoSyncInterval: 30000,
293
- syncOnReconnect: true,
294
- strategy: 'last-write-wins'
295
- }
296
- })
297
-
298
- // Works offline. Automatically syncs when online.
299
- function TodoList() {
300
- const [todos, setTodos] = useSyncedState('todos')
301
-
302
- const addTodo = (text) => {
303
- setTodos([...todos, { id: Date.now(), text }])
304
- // Synced automatically! ✨
305
- }
306
-
307
- return <ul>{todos.map(t => <li>{t.text}</li>)}</ul>
308
- }
309
- ```
310
-
311
- ---
312
-
313
- ## ⚡ Advanced Superpowers
314
-
315
- ### Computed Values (Derived State)
316
-
317
- ```tsx
318
- const store = gstate({
319
- firstName: 'John',
320
- lastName: 'Doe'
321
- })
322
-
323
- // Auto-calculated derived state
324
- store.compute('fullName', (get) => `${get('firstName')} ${get('lastName')}`)
325
-
326
- const fullName = store.get('fullName') // "John Doe"
327
- ```
328
-
329
- ### Error Handling
330
-
331
- ```tsx
332
- const store = gstate({ data: null }, {
333
- onError: (error, context) => {
334
- console.error(`Error in ${context.operation}:`, error.message)
335
- // Send to Sentry, Datadog, etc.
336
- }
337
- })
338
- ```
339
-
340
- ### Size Limits (Memory Protection)
341
-
342
- ```tsx
343
- const store = gstate({ data: {} }, {
344
- maxObjectSize: 5 * 1024 * 1024, // Warn if single value > 5MB
345
- maxTotalSize: 50 * 1024 * 1024 // Warn if total > 50MB
346
- })
347
- ```
348
-
349
- ---
350
-
351
- ## 📦 Build Sizes - Choose Your Weapon
352
-
353
- ### Minimal Version (~0.16 KB)
354
- For embedded systems, widgets, IoT:
355
-
356
- ```javascript
357
- import { createStore } from '@biglogic/rgs/core/minimal'
358
-
359
- const store = createStore({ count: 0 })
360
- store.get('count') // → 0
361
- store.set('count', 5) // → true
362
- ```
363
-
364
- ### Full Version (~32 KB)
365
- For production React apps with all features:
366
-
367
- ```javascript
368
- import { gstate, createStore } from '@biglogic/rgs'
369
-
370
- const useCounter = gstate({ count: 0 })
371
- const count = useCounter(s => s.count)
372
- ```
373
-
374
- | Version | Size | Use Case |
375
- |---------|------|----------|
376
- | **Minimal** | 0.16 KB | Embedded, IoT, Widgets |
377
- | **Full** | ~32 KB | React Apps, Enterprise |
378
-
379
- ---
380
-
381
- ## 🧪 Testing - Rock-Solid Reliability
382
-
383
- ```bash
384
- # Run unit tests
385
- npm run test
386
-
387
- # Run E2E tests (Playwright)
388
- npm run test:e2e
389
- ```
390
-
391
- - ✅ **100+ Unit Tests** (Jest) - Core logic, stores, hooks
392
- - ✅ **E2E Tests** (Playwright) - Real browser, cross-tab sync
393
- - ✅ **Concurrency Testing** - Race condition verification
394
- - ✅ **Security Tests** - AES-256, RBAC, GDPR
395
-
396
- ---
397
-
398
- ## 🏗️ Architecture
399
-
400
- ```mermaid
401
- graph TB
402
- subgraph API
403
- A[gstate] --> D[IStore]
404
- B[useStore] --> D
405
- C[createStore] --> D
406
- end
407
-
408
- D --> E[Storage Adapter]
409
- D --> F[Immer Proxy]
410
- D --> G[Plugins]
411
- D --> H[Security]
412
- D --> I[Async Store]
413
-
414
- E --> J[local]
415
- E --> K[session]
416
- E --> L[memory]
417
-
418
- G --> M[UndoRedo]
419
- G --> N[Sync]
420
- G --> O[Schema]
421
- G --> P[Analytics]
422
- ```
423
-
424
- ### Core Components
425
-
426
- | Component | Description |
427
- |-----------|-------------|
428
- | **gstate()** | Creates store + hook in one line |
429
- | **useStore()** | React hook for subscribing to state |
430
- | **createStore()** | Classic store factory |
431
- | **IStore** | Core interface with get/set/subscribe |
432
- | **StorageAdapters** | local, session, memory persistence |
433
- | **Plugins** | Immer, Undo/Redo, Sync, Schema, etc. |
434
- | **Security** | Encryption, RBAC, GDPR consent |
435
-
436
- ---
437
-
438
- ## 📚 Documentation
439
-
440
- - [Getting Started](docs/chapters/02-getting-started.md)
441
- - [Plugin SDK](docs/chapters/05-plugin-sdk.md)
442
- - [Security Architecture](docs/chapters/09-security-architecture.md)
443
- - [Migration Guide](docs/chapters/08-migration-guide.md)
444
- - [API Reference](docs/api.md)
445
-
446
- ---
447
-
448
- ## 🤝 Contributing
449
-
450
- Contributions are welcome! Please read our [contributing guidelines](CONTRIBUTING.md) first.
451
-
452
- ```bash
453
- # Clone and setup
454
- git clone https://github.com/BigLogic-ca/rgs.git
455
- cd rgs
456
- npm install
457
-
458
- # Run tests
459
- npm run test
460
- ```
461
-
462
- ---
463
-
464
- ## 📄 License
465
-
466
- **MIT** © [Dario Passariello](https://github.com/passariello)
467
-
468
- ---
469
-
470
- <div align="center">
471
-
472
- ## 🔥 Built for Those Who Demand **Excellence**
473
-
474
- [![Powered by Immer](https://img.shields.io/badge/Powered%20by-Immer-2ECC71.svg)](https://github.com/immerjs/immer)
475
- [![Typed with TypeScript](https://img.shields.io/badge/Typed%20with-TypeScript-3178C6.svg)](https://www.typescriptlang.org/)
476
- [![Tested with Jest](https://img.shields.io/badge/Tested%20with-Jest-C21325.svg)](https://jestjs.io/)
477
- [![E2E with Playwright](https://img.shields.io/badge/E2E%20with-Playwright-2ECC71.svg)](https://playwright.dev/)
478
-
479
- **Made with ❤️ and a lot of caffè espresso!**
480
-
481
- [⬆ Back to top](#-argis-rgs---reactive-global-state)
482
-
483
- </div>
package/docs/SUMMARY.md DELETED
@@ -1,55 +0,0 @@
1
- # 🌌 Argis (RGS) - Reactive Global State: The Final Guide
2
-
3
- Welcome to the definitive documentation for **Reactive Global State (RGS)**. If you are here, you're likely tired of endless boilerplate, complex configurations, and state management tools that seem to require a PhD in rocket science.
4
-
5
- This documentation is written for everyone: from **easy setup** for those who just want things to work, to **advanced implementation** for those who want to master the engine.
6
-
7
- ---
8
-
9
- ## 🗺️ Summary
10
-
11
- - **[The Philosophy: Panzer vs. Bicycle](chapters/philosophy.md)**
12
- - Reliability and Security as First-Class Citizens.
13
- - The "Ironclad" Core: Simplicity meets Power.
14
-
15
- - **[Quick Start: 30-Second Setup](chapters/getting-started.md)**
16
- - Deploying the RGS Panzer in your React project.
17
-
18
- - **[The Magnetar Way: One-Liner Power](chapters/the-magnetar-way.md)**
19
- - Creating stores and hooks simultaneously. Types included.
20
-
21
- - **[Persistence and Safety](chapters/persistence-and-safety.md)**
22
- - Never lose user data again (without localStorage headaches).
23
- - Native immutability with Immer (Stellar Engine).
24
-
25
- - **[Ecosystem and Plugins](chapters/plugins-and-extensibility.md)**
26
- - DevTools, Cross-Tab Sync, Analytics, and Typed Plugins.
27
-
28
- - **[Plugin SDK: Build Your Own Extensions](chapters/plugin-sdk.md)**
29
- - Create custom plugins with lifecycle hooks.
30
- - Register methods via `store.plugins`.
31
- - Full API reference and examples.
32
-
33
- - **[Case Studies: Real World Strategies](chapters/case-studies.md)**
34
- - **E-commerce**: Cart isolation and atomic updates.
35
- - **Dashboards**: Multi-store strategies and complex flows.
36
-
37
- - **[Architectural Insights (FAQ)](chapters/07-faq.md)**
38
- - Honest answers on security, performance, and Proxies.
39
-
40
- - **[Migration Guide](chapters/migration-guide.md)**
41
- - Upgrading to latest version (Enterprise Isolation)
42
- - Upgrading to previous version (`secure` → `encoded`)
43
-
44
- - **[Security Architecture & Hardening](chapters/security-architecture.md)**
45
- - Advanced XSS prevention and deep cloning reliability.
46
- - AES-256-GCM and RBAC.
47
-
48
- - **[Local-First Sync Engine](chapters/local-first-sync.md)**
49
- - Offline-by-default with automatic background sync.
50
- - Conflict resolution strategies (last-write-wins, merge, etc.).
51
- - `useSyncedState` hook for React components.
52
-
53
- ---
54
-
55
- > *"Make things simple, but not simpler than necessary."* – RGS Team
package/docs/_config.yml DELETED
@@ -1 +0,0 @@
1
- theme: jekyll-theme-modernist
@@ -1,69 +0,0 @@
1
- # 🛒 Chapter 6: Case Studies - Real Strategies
2
-
3
- In this chapter, we put theory aside and see how RGS solves the problems that keep you up at night (or at least frustrated in the office).
4
-
5
- ---
6
-
7
- ## 🍎 Case 1: High-Performance E-commerce
8
-
9
- **The Problem**: A shopping cart with 50 items, complex sidebar filters, and a product list that must update without "jumping" the whole page.
10
-
11
- **The RGS Strategy**:
12
-
13
- 1. **Atomic Filters**: Don't save the entire filters object. Use separate keys (`category`, `priceRange`, `search`). This way, if the user only changes the price, the search bar doesn't re-render.
14
- 2. **Persistent Cart**: Use `gstate` with a `cart` namespace.
15
- 3. **Computed State for Totals**:
16
-
17
- ```javascript
18
- cartStore.compute('totalAmount', ['items'], (s) =>
19
- s.items.reduce((acc, curr) => acc + curr.price, 0)
20
- );
21
- ```
22
-
23
- **Why do this?** Because the component displaying the total price updates *only* when the `items` array changes, not when the user's name or shipping address changes. **Zero waste.**
24
-
25
- ---
26
-
27
- ## 📊 Case 2: Real-time Dashboard (Sockets/Events)
28
-
29
- **The Problem**: You receive thousands of updates via WebSocket (e.g., crypto prices or server notifications), and React can't keep up.
30
-
31
- **The RGS Strategy**:
32
-
33
- 1. **Atomic Transactions**: In RGS, you can group updates.
34
-
35
- ```javascript
36
- socket.on('bulk_update', (data) => {
37
- store.transaction(() => {
38
- data.forEach(item => store.set(`price_${item.id}`, item.price));
39
- });
40
- });
41
- ```
42
-
43
- **Why do this?** Instead of triggering 100 React updates, the `transaction` triggers **only one** at the end. Your dashboard's performance will go from "tractor" to "Ferrari".
44
-
45
- ---
46
-
47
- ## 🏦 Case 3: Multi-Step Forms (User Onboarding)
48
-
49
- **The Problem**: A signup form with 5 steps. If the user hits "Back" or refreshes the page, they lose everything.
50
-
51
- **The RGS Strategy**:
52
-
53
- 1. Use a dedicated `gstate` called `onboarding`.
54
- 2. Enable `persist: true`.
55
- 3. At each step, just call `set('step1', values)`.
56
- **Why do this?** Because you don't have to manage manual saving logic. When the user returns, the fields are already populated. At the very end (Step 5), call `store.destroy()` to clean up. Clean and elegant.
57
-
58
- ---
59
-
60
- ## 🛡️ Message for Advanced Architects
61
-
62
- *"But I could do all this with a custom cache and an event bus..."*
63
- Sure you could. You could also walk to work instead of driving. But RGS is the car: it's tested, it handles edge cases (closed tabs, full storage, corrupted types), and it lets you focus on **business logic**, not infrastructure.
64
-
65
- Stop reinventing the wheel. Use RGS.
66
-
67
- ---
68
-
69
- **Next step:** [FAQ: For the Skeptics and the Curious](07-faq.md)
@@ -1,53 +0,0 @@
1
- # ❓ Chapter 7: FAQ - Architectural Insights
2
-
3
- This section provides technical context for the design decisions behind RGS (Argis) - Reactive Global State.
4
-
5
- ## 1. "Why integrate Security and GDPR into the State layer?"
6
-
7
- **The Rationale:** In enterprise environments, ensuring that every data access is authorized is critical. By integrating **RBAC** and **Auditing** directly into the store instance, we provide a "Secure-by-Default" architecture. This prevents common oversights where developers might forget to apply permission checks in custom middleware or component logic.
8
-
9
- ## 2. "How does RGS compare to the React Context API?"
10
-
11
- **The Technical Difference:** Context is a dependency injection tool. When values change, React often triggers broad re-renders across the consumer tree. RGS uses a **Surgical Subscription** model. Only components observing a specific key are notified of changes, ensuring optimal performance even in data-heavy applications.
12
-
13
- ## 3. "Is there a performance overhead for Safety Features?"
14
-
15
- **The Trade-off:** Capabilities like deep freezing (immutability) and sanitization do introduce a small computational cost (typically 1-2ms). We believe this is a worthwhile investment to prevent accidental state mutations and security vulnerabilities. For performance-critical scenarios (like high-frequency animations), these features can be selectively disabled.
16
-
17
- ## 4. "How is Type Safety handled with string keys?"
18
-
19
- **The Approach:** String keys provide the flexibility needed for dynamic and runtime-generated state namespaces. For developers requiring strict type safety, RGS offers the `gstate` factory and `GStatePlugins` augmentation, allowing you to define a fully typed interface for your store and its plugins.
20
-
21
- ## 5. "What logic dictates the use of 'Ghost Stores'?"
22
-
23
- **Operational Resilience:** Many applications experience race conditions during hydration or initialization. Instead of allowing the application to crash due to an uninitialized reference, RGS returns a protective Proxy. This Proxy logs a developer warning while providing a safe fallback, ensuring the user interface remains functional while the developer addresses the initialization sequence.
24
-
25
- ## 6. "Is it compatible with modern React patterns (SSR/Next.js)?"
26
-
27
- **Yes.** RGS is built on top of `useSyncExternalStore` and is fully compatible with Concurrent Rendering and Server-Side Rendering (SSR). It works seamlessly with Next.js, Remix, and other modern frameworks without hydration mismatch issues.
28
-
29
- ## 7. "Where do the best practices and improvements come from?"
30
-
31
- **The Process:** All improvements and best practices are based on:
32
-
33
- - **Official React Documentation** - useSyncExternalStore for SSR, hooks rules, React 18/19 features
34
- - **TypeScript Best Practices** - Type safety patterns, generics, strict mode
35
- - **Security Standards** - OWASP for XSS prevention, AES-256-GCM encryption, RBAC patterns
36
- - **Community Libraries** - Patterns from Zustand, Redux, Jotai for plugin architecture
37
- - **Enterprise Patterns** - Error handling, multi-store isolation, GDPR compliance
38
-
39
- Key fixes (like security isolation per-store, Immer optional loading) come from common issues in similar libraries.
40
-
41
- ---
42
-
43
- ## 🛑 Best Practices: Maximizing Reliability
44
-
45
- 1. **State Granularity**: Use RGS for global, persistent, or secured data. For transient UI state (like toggle transitions), standard `useState` is more appropriate.
46
- 2. **Namespace Management**: Always define a unique namespace for your store to prevent data collisions in shared domain environments.
47
- 3. **Rule Validation**: Ensure your RBAC rules are tested against your expected key patterns to maintain a robust security posture.
48
-
49
- ---
50
-
51
- ## 👋 Conclusion
52
-
53
- RGS is designed for teams that prioritize long-term maintainability and system stability. By handling the complexities of security and persistence at the architectural level, we allow developers to focus on building features with confidence.