react-state-basis 0.2.1 → 0.2.2

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.
Files changed (2) hide show
  1. package/README.md +95 -346
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -2,138 +2,73 @@
2
2
  <img src="./assets/logo.png" width="300" alt="Basis Logo">
3
3
  </p>
4
4
 
5
- [![npm version](https://img.shields.io/npm/v/react-state-basis.svg?style=flat-square)](https://www.npmjs.com/package/react-state-basis)
6
- [![View on GitHub](https://img.shields.io/badge/View_Documentation-GitHub-black?logo=github)](https://github.com/liovic/react-state-basis#readme)
7
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
5
+ <div align="center">
8
6
 
9
7
  # 📐 REACT-STATE-BASIS
10
8
  ### **Behavioral State Analysis for React**
11
9
 
12
- It observes how state variables change over time to identify strong correlations that indicate architectural redundancy.
13
-
14
- ---
15
-
16
- **TL;DR:**
17
- React-State-Basis watches your state like a mathematician: every `useState`, `useReducer`, and even `useEffect`-driven update becomes a tracked signal that turns into a time-series vector. When two signals move identically over time, they're collinear (redundant) - and Basis instantly flags it with location, math details, and a copy-paste refactor to derived state.
18
-
19
- ---
20
-
21
- **React-State-Basis** is a real-time architectural auditing engine that treats a React application as a **dynamic system of discrete-time vectors**. Instead of static linting, which only analyzes syntax, Basis monitors the **State Space Topology** of your application to detect mathematical redundancy (collinearity) and synchronization anti-patterns in real-time.
10
+ [![npm version](https://img.shields.io/npm/v/react-state-basis.svg?style=flat-square)](https://www.npmjs.com/package/react-state-basis)
11
+ [![GitHub stars](https://img.shields.io/github/stars/liovic/react-state-basis.svg?style=flat-square)](https://github.com/liovic/react-state-basis/stargazers)
12
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
22
13
 
23
- Inspired by the work of **Sheldon Axler** (*"Linear Algebra Done Right"*), Basis aims to enforce a mathematically optimal "Source of Truth" by ensuring your application state forms a **Basis**.
14
+ </div>
24
15
 
25
16
  ---
26
17
 
27
- ## Installation
18
+ ### The Core Concept
19
+ In Linear Algebra, a **Basis** is a set of linearly independent vectors that span a space. **Basis** treats your React application as a dynamic system where every state variable is a signal over time.
28
20
 
29
- ```bash
30
- npm i react-state-basis
31
- ```
21
+ If two states always update in lockstep, they are **linearly dependent** (redundant). Basis detects these "Dimension Collapses" at runtime and suggests refactoring to derived state (`useMemo`).
32
22
 
33
23
  ---
34
24
 
35
- ## The Philosophy: State as a Vector Space
36
-
37
- In a perfectly architected application, every state variable should represent a **unique dimension of information**.
38
-
39
- Mathematically, your state variables $(v_1, v_2, \dots, v_n)$ should form a **Basis** for your application's state space $V$. A Basis must be **linearly independent**. If two variables update in perfect synchronization, they are **collinear** (linearly dependent). This creates:
40
- 1. **Redundant Renders:** Multiple cycles for a single logical change.
41
- 2. **State Desynchronization:** High risk of "impossible states" (e.g., `user` exists but `isLoggedIn` is false).
42
- 3. **Architectural Entropy:** High cognitive load in tracing data causality.
43
-
44
- ---
45
- ## See It In Action
46
-
47
- ### Detecting Causal Links & Double Renders
48
- ![alt text](./example/screenshots/causal.gif)
49
-
50
- **The Problem:** Manually syncing `fahrenheit` via `useEffect` creates a "Double Render Cycle" (React renders once for Celsius, then again for Fahrenheit).
51
-
52
- **The Basis Solution:** Basis identifies this sequential dependency in real-time. It flags the `Causal Link` and provides a copy-paste refactor to move from expensive state synchronization to a pure **Mathematical Projection** (`useMemo`).
53
-
54
- ### Identifying Boolean Entanglement
55
- ![alt text](./example/screenshots/booleanEntanglement.gif)
56
-
57
- **The Problem:** Using multiple boolean flags (`isLoading`, `isSuccess`, `hasData`) often leads to "impossible states" and redundant updates.
58
-
59
- **The Basis Discovery:** Even though these are separate variables, Basis monitors their transition vectors and detects they are **perfectly synchronized**.
60
-
61
- **The Insight:** It flags a **Dimension Collapse**, alerting you that 3 independent state variables are actually spanning only 1 dimension of information. It suggests consolidating them into a single state machine or a status string.
62
-
63
- ### Circuit Breaker (Infinite Loop Protection)
64
- ![Infinite Loop GIF](./example/screenshots/infiniteLoopTrap.gif)
65
-
66
- **The Trap:** A recursive `useEffect` that triggers an infinite state oscillation, a common mistake that usually freezes the browser's main thread.
67
-
68
- **The Intervention:** Basis acts as a real-time stability monitor. If it detects a high-frequency state oscillation (e.g., 25 updates within 500ms), it automatically activates the **Circuit Breaker**.
69
-
70
- **The Result:** The engine forcefully halts the update chain before the browser locks up. It provides a critical diagnostic report with the exact location of the loop, allowing you to fix the bug without having to kill the browser process.
71
-
72
- ### Cross-Context Dependency Audit
73
- ![Cross-Context Sync GIF](./example/screenshots/initiateGlobalSync.gif)
74
-
75
- **The Scenario:** Modern apps often split state into multiple providers (e.g., `AuthContext` and `ThemeContext`). While architecturally decoupled, they are often **manually synchronized** in logic (e.g., switching to "dark theme" every time a user logs in).
76
-
77
- **The Global Discovery:** Basis performs a **Global State Space Audit**. It doesn't care where your state lives in the component tree; it only cares about the **temporal signals**.
78
-
79
- **The Insight:** By initiating a "Global Sync," Basis identifies that `user` and `theme` are moving in perfect synchronization. It exposes **hidden coupling** between disparate parts of your architecture.
80
-
81
- **The Benefit:** This helps architects identify states that should potentially be merged or derived from a single source of truth, even when they are physically separated across different providers.
25
+ ## How it Works: The Vectorization Engine
82
26
 
83
- ### System Health & Structural Audit
84
- ![System Health Report](./example/screenshots/systemHealthReport.gif)
27
+ Basis doesn't care about the *values* of your state. It monitors the **topology of transitions**.
85
28
 
86
- **System Rank & Efficiency:** Basis performs a global audit of your state space to calculate its **Mathematical Rank**—the actual number of independent information dimensions. An efficiency of **40% (Rank: 4/10)** warns you that 60% of your state is mathematically redundant.
29
+ ### 1. The System Tick
30
+ The engine groups all state updates occurring within a **20ms window** (aligned with the 60FPS frame budget) into a single **System Tick**.
87
31
 
88
- **Redundancy Clusters:** Instead of a raw matrix, Basis automatically groups "entangled" variables into **Redundancy Clusters**. Whether they are booleans in a single component or states across different contexts, Basis identifies them as a single, collapsed dimension if they move in perfect sync.
32
+ ### 2. State-to-Vector Mapping
33
+ Every hook is mapped to a vector $v$ in a 50-dimensional space $\mathbb{R}^{50}$ representing a sliding window of the last 50 ticks:
34
+ * `1` = State transition occurred during this tick.
35
+ * `0` = State remained stagnant.
89
36
 
90
- **Cross-Context Discovery:** The report exposes hidden dependencies across your entire tree (e.g., identifying that `theme` in one context is perfectly correlated with `user` in another).
37
+ **Example of two redundant (collinear) states:**
38
+ ```text
39
+ State A: [0, 1, 0, 0, 1, 0, 1, 0, 1, 0] <-- vA
40
+ State B: [0, 1, 0, 0, 1, 0, 1, 0, 1, 0] <-- vB
41
+ Result: Cosine Similarity = 1.00 (REDUNDANT)
42
+ ```
91
43
 
92
- **Architectural KPI:** Use the **Efficiency Score** as a real-time health metric. Your goal is to reach **100% Efficiency**, where every state variable in your application is linearly independent and serves as a true "Source of Truth."
44
+ Basis detects synchronization, not identity. Even if the data inside the hooks is different, if they always change at the same time, they are collinear in the state-space."
93
45
 
94
- Try the full interactive demo here: [/example](./example)
46
+ ### 3. Real-time Auditing
47
+ Every 5 ticks, Basis calculates the **Cosine Similarity** between all active state vectors. If similarity exceeds **0.88**, an architectural alert is triggered in your console with a suggested fix.
95
48
 
96
49
  ---
97
50
 
98
- ## How react-state-basis is different from existing tools
99
-
100
- There are many great tools for React state management and debugging. Basis doesn't try to replace them - it solves a very specific pain point that most of them don't address directly: detecting behavioral redundancy at runtime (when two or more states always change together, even if they contain different values).
101
-
102
- Here's a quick comparison:
103
-
104
- | Tool / Approach | Static analysis | Runtime behavior tracking | Detects temporal synchronization | Gives refactor suggestions | Overhead in production | Focus on mathematical independence |
105
- |----------------------------------|-----------------|----------------------------|----------------------------------|----------------------------|------------------------|-------------------------------------|
106
- | ESLint + plugins (no-redundant-state, etc.) | ✅ | ❌ | ❌ | Partial (rules only) | None | ❌ |
107
- | React DevTools | ❌ | Partial (component tree) | ❌ | No | Low | ❌ |
108
- | Why Did You Render | ❌ | ✅ (render tracking) | Partial (render causes) | No | Removable | ❌ |
109
- | Redux/Zustand DevTools | ❌ | ✅ (store changes) | ❌ (only store level) | No | Removable | ❌ |
110
- | react-state-basis (Basis) | Partial (Babel) | ✅ | ✅ (tick-based sync detection) | ✅ (copy-paste useMemo) | Zero (change imports) | ✅ (inspired by linear algebra) |
111
-
112
- Basis shines when:
113
- - You have manual state syncing (`setA → setB` in effects/onClick/etc.)
114
- - Multiple booleans or flags that are always updated together
115
- - You want to know which state is the true "source of truth" without guessing
116
- - You want runtime insights that linters can't see (because they don't run the code)
117
-
118
- It is not trying to be a full state manager, linter replacement, or performance profiler.
119
- It is a specialized diagnostic tool for one very common anti-pattern - and it tries to do that one thing really well.
120
-
51
+ ## Ghost Mode: Zero-Overhead Production
52
+ Basis is a **development-only** infrastructure. Using **Conditional Exports**, it automatically swaps itself for a "Zero-Op" version in production:
53
+ * **Development:** Full Linear Algebra engine and auditor active.
54
+ * **Production:** Exports raw React hooks directly. **Zero bundle bloat. Zero performance penalty.**
121
55
 
122
56
  ---
123
57
 
124
- ## 🚀 Setup & Integration
125
-
126
- To enable the mathematical monitoring of your application, follow these two steps:
58
+ ## Quick Start
127
59
 
128
- ### 1. Initialize the Basis Monitor
129
- Wrap your application root with the `BasisProvider`.
60
+ ### 1. Install
61
+ ```bash
62
+ npm i react-state-basis
63
+ ```
130
64
 
65
+ ### 2. Initialize
131
66
  ```tsx
132
67
  import { BasisProvider } from 'react-state-basis';
133
68
 
134
69
  export default function Root() {
135
70
  return (
136
- <BasisProvider debug={true}>
71
+ <BasisProvider debug={true}> {/* Set debug={false} for total silence in dev */}
137
72
  <App />
138
73
  </BasisProvider>
139
74
  );
@@ -144,7 +79,7 @@ export default function Root() {
144
79
  * `true` (Default): Enables the real-time diagnostic dashboard, visual system status badge (Web only), and detailed console auditing (including the Circuit Breaker).
145
80
  * `false`: Completely deactivates the Basis engine. No background analysis, no memory consumption, and no logging. The "Circuit Breaker" is also disabled in this mode to allow for a zero-overhead, raw React experience in development.
146
81
 
147
- ### 2. Use Drop-in Replacement Imports
82
+ ### 3. Drop-in Replacement
148
83
  Replace your standard React hook imports with `react-state-basis`. This allows the engine to instrument your state updates without changing your component logic.
149
84
 
150
85
  **Standard Named Imports (Recommended):**
@@ -181,28 +116,13 @@ function MyComponent() {
181
116
  const [count, setCount] = Basis.useState(0); // Also tracked automatically
182
117
  }
183
118
  ```
119
+ ---
184
120
 
185
- ## Ghost Mode: Zero-Overhead Production
186
- Basis is a **development-only** infrastructure.
187
-
188
- Using **Conditional Exports**, Basis automatically detects your environment:
189
- * **Development:** The full Linear Algebra engine and auditor are active.
190
- * **Production:** Basis swaps itself for a **Zero-Op version**. It exports raw React hooks directly with no additional logic, ensuring **zero bundle bloat** and **zero performance penalty** for your end users.
191
-
192
- You can safely keep `react-state-basis` in your code without manual removal before deployment.
193
-
194
- ### 3. The Babel plugin
195
- The Babel plugin is optional but highly recommended. Without it, state variables will be tracked as anonymous_state, making it difficult to identify specific redundancies in large applications. You can also manually provide a label as the last argument to any hook if you prefer not to use Babel.
196
-
197
- > If you choose not to use the Babel plugin, you can still get specific labels by passing a string as the last argument:
198
-
199
- ```tsx
200
- const [count, setCount] = useState(0, "MyComponent -> count");
201
- ```
202
-
203
- To get the most out of Basis, you should enable the Babel plugin. This automatically injects the **filename** and **variable name** into your hooks so you don't have to label them manually.
121
+ ## Automated Diagnostics (Babel)
122
+ While Basis works out of the box, hooks will be labeled as `anonymous_state` by default. To get the rich diagnostics seen in the demos (with automatic **filenames** and **variable names**), we highly recommend using our Babel plugin.
204
123
 
205
- If you are using **Vite**, add the following to your `vite.config.ts`:
124
+ ### Vite Integration
125
+ Add Basis to your `vite.config.ts`. It will automatically instrument your hooks during build time:
206
126
 
207
127
  ```typescript
208
128
  // vite.config.ts
@@ -214,7 +134,6 @@ export default defineConfig({
214
134
  react({
215
135
  babel: {
216
136
  // Automatically labels useState, useMemo, etc.
217
- // for richer diagnostics in the console.
218
137
  plugins: [['react-state-basis/plugin']]
219
138
  }
220
139
  })
@@ -222,257 +141,87 @@ export default defineConfig({
222
141
  })
223
142
  ```
224
143
 
144
+ ### Manual Labeling (Alternative)
145
+ If you prefer not to use Babel, you can manually label any hook by passing a string as the last argument:
225
146
 
226
- ---
227
-
228
- ## Technical Architecture
229
-
230
- React-State-Basis utilizes a three-tier instrumentation pipeline to audit your system:
231
-
232
- ### 1. The Compiler Layer (Babel AST)
233
- A build-time plugin performs static analysis, injecting the **filename** and **variable name** directly into the runtime calls. This transforms an anonymous execution graph into a **structured state map**.
234
-
235
- ### 2. The Runtime Layer (Signal Mapping)
236
- Every state transition is intercepted. Basis groups updates occurring within a **16ms window** into a single "System Tick." Each state variable is mapped to a vector in $\mathbb{R}^{50}$.
237
- * `1` = State transition occurred in this tick.
238
- * `0` = State remained stagnant.
239
-
240
- React-State-Basis does not compare state values. It analyzes the timing and synchronization of updates, treating each state variable as a discrete activation signal over time.
241
-
242
- ### 3. The Analysis Layer (The Heuristic)
243
- In pure Linear Algebra, proving linear independence for $N$ variables requires solving the system $a_1v_1 + \dots + a_nv_n = 0$. Using algorithms like Gaussian elimination or SVD to determine the **Rank** of the state matrix has a computational complexity of $O(N^3)$. Running this in a browser runtime for every state update would be prohibitively expensive.
244
-
245
- To maintain real-time performance, React-State-Basis uses **Cosine Similarity** as a high-speed heuristic ($O(D)$, where $D$ is the vector dimension) to detect **pairwise collinearity**:
246
-
247
- ```math
248
- \text{similarity} = \cos(\theta) = \frac{\mathbf{A} \cdot \mathbf{B}}{\Vert \mathbf{A} \Vert \Vert \mathbf{B} \Vert}
249
- ```
250
-
251
- If $\cos(\theta) \approx 1.00$, the vectors are collinear (linearly dependent), and the engine triggers a redundancy alert.
252
-
253
- ---
254
-
255
- ## Real-World Demonstration: The Auth Anti-Pattern
256
-
257
- Developers often manually sync related states, creating a redundant dimension in the Basis:
258
-
259
- ### ❌ Redundant Basis (State Bloat)
260
- ```tsx
261
- const [user, setUser] = useState(null);
262
- const [isLogged, setIsLogged] = useState(false);
263
-
264
- const onLogin = (userData) => {
265
- setUser(userData);
266
- setIsLogged(true); // BASIS ALERT: Always updated in sync with 'user'
267
- };
268
- ```
269
- **Engine Analysis:** The Engine calculates that `user` and `isLogged` are perfectly synchronized. It warns you that you are using two dimensions to describe a 1D problem.
270
-
271
- ### ✅ Independent Basis (Optimal Design)
272
- Basis suggests a **Projection**-transforming a basis vector into a derived value.
273
147
  ```tsx
274
- const [user, setUser] = useState(null);
275
- const isLogged = useMemo(() => !!user, [user]); // Mathematically clean
148
+ const [count, setCount] = useState(0, "MyComponent -> count");
276
149
  ```
277
150
 
278
151
  ---
279
152
 
280
- ## Diagnostic Dashboard
281
-
282
- Basis provides high-end diagnostic feedback directly in your browser console:
283
-
284
- * **Location Tracking:** Identifies exact files and variable names causing redundancy.
285
- * **Refactor Snippets:** Provides dark-themed code blocks you can copy-paste to fix your state architecture.
286
- * **Health Matrix:** Call `printBasisReport()` to see your **Efficiency Score** and the full **Correlation Matrix** of your application.
287
-
288
- ---
289
-
290
- ## Key Features
291
-
292
- * **Content-Agnostic:** Identifies logical links through temporal synchronization, not data types.
293
- * **Circuit Breaker:** Halts high-frequency state oscillations (Infinite Loops) to protect the browser thread.
294
- * **Causal Detective:** Tracks causality chains from `useEffect` to `useState` to identify cascading renders.
295
- * **Zero Lock-in:** Simply point your imports back to `'react'` in production. Basis is a **Development-time verification infrastructure**.
296
-
297
- ---
298
-
299
- ## Mathematical Inspiration
300
-
301
- ### The Basis Theorem
302
- According to Axler (*Linear Algebra Done Right, Definition 2.27*):
153
+ ## High-Level Insights
303
154
 
304
- > A **basis** of $V$ is a list of vectors in $V$ that is **linearly independent** and **spans** $V$.
155
+ ### System Health Report
156
+ For a bird's-eye view of your entire application's state-space, call the global reporter in your browser console:
305
157
 
306
- To satisfy this theorem in the context of application state:
307
-
308
- 1. **Linear Independence:** No state variable in the list can be expressed as a linear combination of the others. If a state $v_n$ can be derived from $\{v_1, \dots, v_{n-1}\}$, the list is linearly dependent and contains redundancy.
309
- 2. **Spanning the Space:** The list of state variables must contain enough information to represent every possible configuration of the user interface.
310
-
311
- React-State-Basis ensures that your state list is a true Basis by identifying and flagging vectors that fail the test of linear independence.
312
-
313
- > *"Linear algebra is the study of linear maps on finite-dimensional vector spaces."*
314
- > - **Sheldon Axler**
158
+ ```javascript
159
+ window.printBasisReport();
160
+ ```
161
+ This generates a correlation matrix and calculates your **Basis Efficiency Score** in real-time.
315
162
 
316
- React-State-Basis bridges the gap between abstract algebra and UI engineering.
317
- By ensuring your application state forms an independent, non-redundant basis, it helps you build software that is inherently more stable, efficient, and easier to reason about.
318
163
  ---
164
+ ### React Native & Expo
319
165
 
320
- ### Implementation of the Linear Dependency Lemma
321
- According to Axler (*Lemma 2.21*), in a linearly dependent **list** of vectors, there exists an index $j$ such that $v_j$ is in the span of the **preceding** vectors ($v_1, \dots, v_{j-1}$).
322
-
323
- **React-State-Basis** implements this sequential logic to audit your state:
324
-
325
- 1. **The Ordered List:** Every state variable is treated as an element in an ordered list $(v_1, v_2, \dots, v_n)$ based on its registration order in the application.
326
- 2. **Sequential Discovery:** As time progresses, the engine monitors the list. It doesn't just look for "similar" vectors; it looks for vectors that **fail to add a new dimension** to the subspace generated by the vectors that came before them.
327
- 3. **Identifying the Redundant Element:** If $v_{isLogged}$ is perfectly correlated with $v_{user}$, the engine identifies that $v_{isLogged} \in \text{span}(v_{user})$. Since $v_{user}$ preceded it, $v_{isLogged}$ is mathematically the redundant element.
328
- 4. **Basis Reduction:** Following the lemma's second conclusion, the engine advises removing $v_j$, proving that the "information span" of your app remains identical while the complexity of the Basis decreases.
166
+ Basis automatically detects the environment. In mobile environments, it switches to **Headless Mode**-disabling the web badge and formatting all diagnostics for the Metro terminal.
329
167
 
330
168
  ---
331
169
 
332
- ## Design Constraints & Heuristics
333
-
334
- React-State-Basis uses probabilistic, time-windowed heuristics to approximate linear dependence.
335
- As with any runtime analysis:
336
-
337
- - Rarely-updated states may appear correlated by chance
338
- - High-frequency UI interactions may trigger conservative warnings
339
- - Results are advisory, not prescriptive
170
+ ## Basis vs Existing Tools
340
171
 
341
- React-State-Basis is designed to **surface architectural questions**, not enforce correctness.
172
+ | Feature | React DevTools | Why Did You Render | Basis 📐 |
173
+ | :--- | :---: | :---: | :---: |
174
+ | **Analyzes Values** | ✅ | ✅ | ❌ (Value-agnostic) |
175
+ | **Tracks Timing/Ticks** | ❌ | ❌ | ✅ |
176
+ | **Detects Redundancy** | ❌ | ❌ | ✅ (Linear Dependence) |
177
+ | **Circuit Breaker** | ❌ | ❌ | ✅ (Halts petlje) |
178
+ | **Prod. Overhead** | Low | Medium | **Zero** (Ghost Mode) |
342
179
 
343
180
  ---
344
181
 
345
- ## Frequently Asked Questions
182
+ ## Key Capabilities
346
183
 
347
- ### **Is React-State-Basis a replacement for React DevTools or linters?**
348
- No.
184
+ ### Redundant State Detection
185
+ Basis monitors transition vectors to identify "Dimension Collapses." When multiple states (like `isLoading`, `isSuccess`) update in lockstep, it suggests consolidating them.
186
+ <br/>
187
+ <img src="./example/screenshots/booleanEntanglement.gif" width="700" alt="Boolean Entanglement Demo" />
349
188
 
350
- React-State-Basis complements existing tools.
351
- Linters analyze **code structure**, and React DevTools show **component behavior**. React-State-Basis analyzes **state relationships over time**-something neither tool is designed to detect.
189
+ ### Causal Detective
190
+ Identifies "Double Render Cycles" by tracking the causality chain from `useEffect` or `useLayoutEffect` to state setters. Basis provides a direct refactor snippet to move from manual sync to a pure mathematical projection (`useMemo`).
191
+ <br/>
192
+ <img src="./example/screenshots/causal.gif" width="700" alt="Causal Link Demo" />
352
193
 
353
- It answers questions like:
354
- - *“Why do these two states always change together?”*
355
- - *“Which state is the true source of truth?”*
356
- - *“Am I manually synchronizing derived data?”*
194
+ ### Circuit Breaker
195
+ A real-time stability monitor. If high-frequency state oscillation is detected (e.g., a recursive effect), Basis forcefully halts the update chain to prevent the browser thread from locking up.
196
+ <br/>
197
+ <img src="./example/screenshots/infiniteLoopTrap.gif" width="700" alt="Circuit Breaker Demo" />
357
198
 
358
- ### **Does this change React behavior or execution order?**
359
- No.
199
+ ### Cross-Context Audit
200
+ Performs a global state space audit to expose hidden coupling between disparate parts of your architecture (e.g., syncing states across different Providers).
201
+ <br/>
202
+ <img src="./example/screenshots/initiateGlobalSync.gif" width="700" alt="Cross-Context Sync Demo" />
360
203
 
361
- React-State-Basis **does not modify React’s scheduling, rendering, or reconciliation**.
362
- It observes state updates at runtime and logs diagnostics during development.
363
-
364
- Removing React-State-Basis restores your application to standard React behavior with no residual effects.
365
-
366
- ### **Is this safe to use in production?**
367
- React-State-Basis is designed for **development-time analysis**.
368
-
369
- Minimal in development, zero in production via Ghost Mode.
370
-
371
- For production builds, simply switch your imports back to `'react'` or keep as is.
372
-
373
- ### **How accurate is the redundancy detection?**
374
- React-State-Basis uses **time-windowed behavioral analysis**, not formal proofs.
375
-
376
- This means:
377
- - Strong, consistent correlations are highly reliable indicators of redundancy
378
- - Rare or coincidental correlations may trigger conservative warnings
379
-
380
- All results are **advisory** and should be interpreted as architectural signals, not errors.
381
-
382
- ### **Can this detect all redundant state?**
383
- No-and that’s intentional.
384
-
385
- React-State-Basis detects **behavioral redundancy**, not semantic equivalence.
386
- Two states may contain the same *data* but update independently, which is architecturally valid.
387
-
388
- React-State-Basis only flags redundancy when two states behave as a single information dimension over time.
389
-
390
- ### **Why not just use selectors or derived state manually?**
391
- You should-and React-State-Basis encourages that.
392
-
393
- The challenge is *finding* where derived state should exist in large or evolving codebases. React-State-Basis helps identify:
394
- - state that should be derived
395
- - state that is unintentionally synchronized
396
- - state that adds no new information
397
-
398
- It surfaces opportunities for refactoring, not rules you must follow.
399
-
400
- ### **Does this work with Redux, Zustand, or other state managers?**
401
- React-State-Basis currently instruments **React hooks directly**.
402
-
403
- However, the underlying model is store-agnostic. Any system with:
404
- - discrete state updates
405
- - identifiable update points
406
- - consistent labeling
407
-
408
- could theoretically be analyzed using the same approach.
409
-
410
- ### **What about performance?**
411
- React-State-Basis is optimized for real-time use in development.
412
-
413
- Key design choices:
414
- - Fixed-size sliding windows
415
- - O(D) similarity checks
416
- - Batched analysis every N ticks
417
-
418
- For typical applications, overhead is negligible. For extremely high-frequency updates (e.g., animations), React-State-Basis may emit conservative warnings.
419
-
420
- ### **Is this “formal verification”?**
421
- No.
422
-
423
- React-State-Basis performs **runtime architectural auditing**, not formal mathematical verification.
424
- It applies concepts from linear algebra to **observe and analyze behavior**, not to prove correctness.
425
-
426
- ### **Who is this tool for?**
427
- React-State-Basis is best suited for:
428
- - Medium to large React applications
429
- - Codebases with complex state interactions
430
- - Engineers debugging synchronization bugs
431
- - Teams prioritizing architectural clarity
432
-
433
- It may be unnecessary for small or short-lived projects.
434
-
435
- ### **Why linear algebra?**
436
- Because state redundancy *is* linear dependence.
437
-
438
- If two state variables always change together, they span the same dimension of information. Linear algebra provides a precise language-and useful tools-for detecting and reasoning about that relationship.
439
-
440
- ### **Will this ever produce false positives?**
441
- Yes.
442
-
443
- React-State-Basis favors **visibility over silence**.
444
- When in doubt, it surfaces potential issues so developers can make informed decisions.
445
-
446
- Think of it as an architectural smoke detector-not a fire marshal.
204
+ ### System Health & Efficiency Audit
205
+ Basis performs a global audit of your state space to calculate its **Mathematical Rank**-the actual number of independent information dimensions. Use the **Efficiency Score** as a real-time KPI for your architecture.
206
+ <br/>
207
+ <img src="./example/screenshots/systemHealthReport.gif" width="700" alt="System Health Report Demo" />
447
208
 
448
209
  ---
449
210
 
450
- ## Roadmap: The Path to Architectural Rigor
211
+ ## Roadmap
451
212
 
452
- React-State-Basis is evolving from a runtime auditor to a complete development infrastructure. Here is the planned trajectory:
213
+ #### **v0.2.x - Stability & Universal Support (Current)**
214
+ - [x] Full React Hook API parity & React Native support.
215
+ - [x] Memory-optimized "Ghost Registration" logic.
216
+ - [x] 95% Test Coverage verified engine.
453
217
 
454
- #### **v0.2.0 Full Hook Parity (DONE)**
455
- * **Complete API Coverage:** Added support for the entire React hook suite.
456
- * **Babel Enhancements:** Automated labeling for all hooks via AST transformation.
457
- * **Signature Robustness:** Smart disambiguation between dependency arrays and manual labels.
218
+ #### **v0.3.0 - Visuals & React 19** 📈
219
+ - [ ] **State-Space Visualizer:** 2D topology map showing redundancy clusters.
220
+ - [ ] **CLI Utilities:** `rsb-init` and `rsb-clean` for automated codemods.
221
+ - [ ] **React 19 Native Support:** `use()`, `useOptimistic()`, `useActionState()`.
458
222
 
459
- #### **v0.2.1 — Performance & Safety (DONE)** ✅
460
- * **Universal Support:** Environment detection (`isWeb`) to prevent crashes in **React Native** and **Expo**.
461
- * **Memory Optimization:** "Ghost registration" logic to ensure zero memory footprint when `debug={false}`.
462
- * **Centralized Config:** Unified engine state to prevent logging "leaks" during initialization.
463
-
464
- #### **v0.3.0 — Modernity & Visual Ecosystem (Upcoming)**
465
- * **React 19 Support:** Native integration for `use()`, `useOptimistic()`, and `useActionState()`.
466
- * **CLI Utilities (`rsb-init`, `rsb-clean`):** Automated codemods to instantly inject or remove Basis from large codebases.
467
- * **State-Space Visualizer:** A 2D topology map showing "Redundancy Clusters" to visualize your architecture's geometry.
468
-
469
- #### **v1.0.0 — Formal Verification**
470
- * **Architectural Gatekeeping:** CI/CD integration to fail builds on critical dimension collapses.
471
223
  ---
472
224
 
473
- ### 📬 Get Involved
474
- If you have an idea for a mathematical heuristic or a DX improvement, feel free to open an issue or a PR.
475
-
476
- ---
477
- *Developed by LP*
478
- *For engineers who treat software as applied mathematics.* 📐
225
+ <div align="center">
226
+ Developed by LP | For engineers who treat software as applied mathematics. 🚀
227
+ </div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-state-basis",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "A linear algebra-powered React architectural tool that detects redundant state and synchronization anti-patterns by modeling state transitions as vectors in a basis.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",