universal-state-kit
v1.0.1
Published
A lightweight, universal state management toolkit for JavaScript/TypeScript, React, Next.js, Vue, Angular, Node.js, and offline sync.
Downloads
274
Maintainers
Readme
🚀 Universal State Kit
An ultra-lightweight, zero-dependency state management toolkit to synchronize local and global states seamlessly across browser, Node.js, React, Next.js, Vue, Angular, and React Native applications.
⚡ Key Features
- 🚀 Global & Local State: Easily manage state with lightweight publish-subscribe store mechanics.
- ⏳ Undo / Redo: Time-travel debugging with built-in history and future tracking.
- 💾 IndexedDB & LocalStorage: Automatic persistent caching for tiny or huge state models.
- 📡 Realtime WebSocket Sync: Bidirectional state replication between multiple clients and servers.
- 🛡️ Conflict-Free Convergence: Out-of-the-box LWW-element-set CRDT state reconciliation.
- 🐻 Zustand API Compatibility: Familiar Zustand state creator and selector hook APIs.
- 🧠 AI Predictor & Memory: Linear field pattern prediction and AI Agent memory logs.
- 🌐 Multi-Framework: First-class support for React, Vue, Angular, Node.js, and DevTools.
- 📦 TypeScript Ready: Zero-config compilation with full type safety.
📦 Installation
Choose your favorite package manager:
# npm
npm install universal-state-kit
# yarn
yarn add universal-state-kit
# pnpm
pnpm add universal-state-kit🚀 Quick Start
import { createStore } from "universal-state-kit";
const store = createStore({
user: null,
});
// Subscribe to state updates
const unsubscribe = store.subscribe((state) => {
console.log("State updated:", state);
});
// Update state
store.setState({
user: {
name: "demo",
},
});
console.log(store.getState()); // { user: { name: "demo" } }📖 Usage Examples
1. React Support
import React from "react";
import { createStore } from "universal-state-kit";
import { useStore } from "universal-state-kit/react";
const store = createStore(
{
count: 0,
},
{
persist: true,
devtools: true,
}
);
export default function App() {
const [state, setState] = useStore(store);
return (
<div>
<h1>{state.count}</h1>
<button onClick={() => setState({ count: state.count + 1 })}>
Increment
</button>
</div>
);
}2. Next.js Support (App Router)
"use client";
import { createStore } from "universal-state-kit";
import { useStore } from "universal-state-kit/react";
const store = createStore({
theme: "dark",
});
export default function Home() {
const [state, setState] = useStore(store);
return (
<div>
<p>Current theme: {state.theme}</p>
<button
onClick={() =>
setState({
theme: state.theme === "dark" ? "light" : "dark",
})
}
>
Toggle Theme
</button>
</div>
);
}3. Vue Support
import { createVueStore } from "universal-state-kit/vue";
const store = createVueStore({
count: 0,
});
// Update state Reactively
store.setState({
count: 1,
});
console.log(store.state.count); // 14. Angular Support
import { AngularStore } from "universal-state-kit/angular";
const store = new AngularStore({
user: null,
});
// Subscribe to RxJS Observable
store.getState().subscribe((state) => {
console.log("Angular State:", state);
});5. API Cache Module
import { cachedFetch } from "universal-state-kit";
const users = await cachedFetch(
"https://jsonplaceholder.typicode.com/users"
);6. Offline Sync
import { OfflineQueue } from "universal-state-kit";
const queue = new OfflineQueue();
// Add deferred tasks
queue.add(async () => {
console.log("Sync API call 1 to server...");
});
// Process the queue when back online
queue.process();7. Zustand Compatibility Layer
Import from universal-state-kit/zustand to create stores using the familiar Zustand state creator pattern:
import React from "react";
import { create } from "universal-state-kit/zustand";
const useBearStore = create((set, get) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}));
export default function BearCounter() {
// Use as a reactive hook
const bears = useBearStore((state) => state.bears);
const increase = useBearStore((state) => state.increasePopulation);
return (
<div>
<h2>Bears: {bears}</h2>
<button onClick={increase}>Add Bear</button>
</div>
);
}
// Can also be used outside React components
console.log(useBearStore.getState().bears);8. Conflict-Free Replicated Data Types (CRDT) Support
Supports Last-Write-Wins (LWW) conflict-free convergence updates across multiple nodes:
import { createCRDTState, mergeCRDT } from "universal-state-kit/crdt";
let replicaA = createCRDTState({ count: 10, name: "Alice" });
let replicaB = createCRDTState({ count: 10, name: "Bob" });
// Modify replica A (simulating local update at time T1)
replicaA.name = "Charlie";
replicaA._timestamps.name = Date.now();
// Merge modifications from replica A into replica B
const merged = mergeCRDT(replicaB, replicaA);
console.log(merged.name); // "Charlie"9. WebSocket Realtime Sync
Allows bidirectional state replication between clients and a server:
import { createStore } from "universal-state-kit";
import { WebSocketSyncManager } from "universal-state-kit/sync";
const store = createStore({ value: "Initial" });
const syncManager = new WebSocketSyncManager(store, "ws://localhost:8080/sync");
// Connect and begin syncing
syncManager.connect();10. IndexedDB Offline Storage
Allows storing massive state datasets locally without hitting localStorage size caps:
import { IndexedDBStorage } from "universal-state-kit/indexeddb";
const storage = new IndexedDBStorage("LargeAppDB", "settings");
// Read and write async
await storage.set("theme", { color: "emerald", font: "Inter" });
const config = await storage.get("theme");
console.log(config); // { color: "emerald", font: "Inter" }11. AI Predictions & AI Agent Memory
Integrates predictive state modeling and AI agent conversation history tracking:
import { AIStatePredictor, AIAgentMemory } from "universal-state-kit/ai";
// A. AI State Prediction
const predictor = new AIStatePredictor();
// Record linear state transitions
predictor.recordTransition({ count: 10 });
predictor.recordTransition({ count: 20 });
predictor.recordTransition({ count: 30 });
// Predict next state
const prediction = predictor.predictNextState({ count: 40 });
console.log(prediction); // { count: 50 } (predicted next value)
// B. AI Agent Memory
const memory = new AIAgentMemory();
memory.addMessage("user", "Hello agent, what is the server status?");
memory.recordToolCall("checkServer", { port: 80 }, { status: "online" });
memory.addMessage("assistant", "The server is online.");
console.log(memory.getFormattedHistory());
// "USER: Hello agent, what is the server status?\n\nASSISTANT: The server is online."12. SSR Hydration
import { createStore } from "universal-state-kit";
const store = createStore({ user: null });
// Hydrate state from server-side load (e.g. Next.js getServerSideProps)
store.hydrate({ user: { name: "Prakash" } });🛠️ Developer Guide & Building
To install development dependencies and compile the bundles:
# Install dependencies
npm install
# Build production bundles
npm run buildThe output bundles will be created in the dist directory with clean ESM/CommonJS and Type declaration (d.ts) mappings.
📄 License
MIT
