DEV Community

Cover image for I used Linear Algebra to audit my React state (and built a tool for it)
Petar Liovic
Petar Liovic

Posted on

I used Linear Algebra to audit my React state (and built a tool for it)

The Problem: State Entropy

In large React apps, we often end up manually synchronizing related states. We've all seen (or written) code like this:

const [user, setUser] = useState(null);
const [isLoggedIn, setIsLoggedIn] = useState(false);

const onLogin = (data) => {
   setUser(data);
   setIsLoggedIn(true); // Redundant?
};
Enter fullscreen mode Exit fullscreen mode

From a systems engineering perspective, this UI has a redundant degree of freedom. isLoggedIn is not an independent source of truth; it's a projection of user.

The Theory: State as a Vector

I recently went down the rabbit hole of Linear Algebra (inspired by Axler’s Linear Algebra Done Right). I realized that we can treat every React hook (useState, useMemo, useReducer) as a vector in a high-dimensional space.
If two state variables always update in perfect synchronization, they are linearly dependent (collinear). In geometry, this is a Dimension Collapse.

The Result: Basis

I decided to build an auditor that monitors these signals in real-time. It doesn't look at the values of your state; it looks at the timing of updates across a 50-tick sliding window.

Key Features:

Redundancy Detection: Using Cosine Similarity, Basis identifies when multiple states are perfectly correlated and suggests refactoring them into a single source of truth or a useMemo.

Circuit Breaker: It detects high-frequency state oscillations (infinite loops) and kills the update chain before your browser tab locks up.

Causal Tracking: It identifies sequential updates (e.g., useEffect syncing state A to state B) and flags them as "Double Render Cycles."

How it looks

Booleans Example

The Problem: Using multiple boolean flags (isLoading, isSuccess, hasData) often leads to "impossible states" and redundant updates.

The Basis Discovery: Even though these are separate variables, Basis monitors their transition vectors and detects they are perfectly synchronized.

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.


Circuit Breaker

The Trap: A recursive useEffect that triggers an infinite state oscillation, a common mistake that usually freezes the browser's main thread.

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.

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.


Manually Syncing

The Problem: Manually syncing fahrenheit via useEffect creates a "Double Render Cycle" (React renders once for Celsius, then again for Fahrenheit).

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).


Cross Context

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).

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.

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.

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.


Health Check

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.

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.

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).

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."


Why use math for this?

Because architectural debt is often hard to "see" in a large codebase, but it's very easy to "calculate." If your application's Mathematical Rank is lower than the number of state variables you have, you have redundancy.

Try it out

I just released this as an open-source package. I’m looking for honest, technical feedback from engineers who care about state architecture.

GitHub: https://github.com/liovic/react-state-basis
NPM: npm i react-state-basis

It includes a Babel plugin to automatically label your hooks using your actual variable names and filenames.


Thanks for taking the time to check this out. I believe that bringing more mathematical rigor to frontend engineering can save us a lot of architectural headaches. If you find this useful, feel free to star the repo or open an issue with your feedback.

Keep your state minimal and your dimensions independent.

Top comments (0)