Internals: Core Engine Loop
The SoulState core engine is a lean, efficient system designed to manage state updates and propagate changes with minimal overhead. It orchestrates the interaction between the store's state, the set and get methods, and the subscription manager.
The createStore Factory
The engine is instantiated by the createStore factory function, which sets up the initial state and core mechanisms for state manipulation:
// From src/core/store.ts
export function createStore<T extends object>(initialState: T): Store<T> {
let state: T = initialState;
const subscriptionManager = createSubscriptionManager<T>();
// Batching control
let isNotificationScheduled = false;
let lastKnownState = state;
const notifySubscribers = () => {
subscriptionManager.notify(state, lastKnownState);
lastKnownState = state;
isNotificationScheduled = false;
};
const scheduleNotification = () => {
if (!isNotificationScheduled) {
isNotificationScheduled = true;
queueMicrotask(notifySubscribers);
}
};
const get = (): T => state;
const set = (updater: StateUpdater<T>) => {
const partialState = typeof updater === 'function'
? (updater as (state: T) => Partial<T> | T)(state)
: updater;
// Early return for no-op updates
if (Object.is(partialState, state) || partialState === undefined) {
return;
}
// Change detection - check if values actually changed
let hasChanged = false;
const updatedKeys = Object.keys(partialState);
for (let i = 0; i < updatedKeys.length; i++) {
const key = updatedKeys[i] as keyof T;
if (!Object.is(state[key], (partialState as T)[key])) {
hasChanged = true;
break;
}
}
if (!hasChanged) {
return; // Skip object creation and notifications
}
// Create new state object only when necessary
const nextState = { ...state, ...(partialState as Partial<T>) };
state = nextState;
scheduleNotification();
};
const subscribe = <S>(
selector: (state: T) => S,
listener: (selectedState: S, prevSelectedState: S) => void,
options?: { equalityFn?: (a: S, b: S) => boolean }
) => {
return subscriptionManager.subscribe(selector, listener, options?.equalityFn, state);
};
return { get, set, subscribe };
}
State Management Flow
The core engine operates through a continuous optimization cycle:
graph TD
A[Action Triggered] --> B[store.set(updater)];
B --> C{Change Detection};
C -->|No Changes| D[Early Return];
C -->|Changes Found| E[Structural Sharing];
E --> F{Notification Scheduled?};
F -->|No| G[Schedule Microtask];
F -->|Yes| H[Skip Scheduling];
G --> I[Microtask Queue];
H --> I;
I --> J[Execute notifySubscribers];
J --> K[Linked List Traversal];
K --> L{Run Selector & Equality Check};
L -->|Changed| M[Trigger Re-render];
L -->|Unchanged| N[Skip];
M --> O[UI Updates];
N --> K;
Engine Execution Phases
Phase 1: State Update
// 1. Update calculation
const partialState = typeof updater === 'function' ? updater(state) : updater;
// 2. Early optimization checks
if (Object.is(partialState, state) || partialState === undefined) {
return; // No changes needed
}
// 3. Change detection
let hasChanged = false;
const updatedKeys = Object.keys(partialState);
for (let i = 0; i < updatedKeys.length; i++) {
const key = updatedKeys[i] as keyof T;
if (!Object.is(state[key], (partialState as T)[key])) {
hasChanged = true;
break; // Early exit on first change
}
}
// 4. Structural sharing only when necessary
if (!hasChanged) return;
const nextState = { ...state, ...(partialState as Partial<T>) };
state = nextState;
Phase 2: Notification Scheduling
// Microtask batching logic
const scheduleNotification = () => {
if (!isNotificationScheduled) {
isNotificationScheduled = true;
queueMicrotask(notifySubscribers); // Deferred execution
}
};
// Multiple updates → single notification
store.set({ a: 1 }); // First call → schedule
store.set({ b: 2 }); // Already scheduled → skip
store.set({ c: 3 }); // Already scheduled → skip
// Single microtask with all changes
Phase 3: Subscriber Notification
// From src/core/subscriptions.ts
const notify = (newState: T, prevState: T) => {
if (Object.is(newState, prevState)) return;
// Efficient linked list traversal
let current = head;
while (current) {
const sub = current;
const newSelectedState = sub.selector(newState);
const lastState = sub.lastState;
// Selective notification
if (!sub.equalityFn(newSelectedState, lastState)) {
sub.lastState = newSelectedState;
sub.listener(newSelectedState, lastState); // Trigger re-render
}
current = current.next;
}
};
Performance Optimizations
Change Detection
SoulState prevents unnecessary work through intelligent change detection:
// Instead of blind object creation:
// const nextState = { ...state, ...partialState }; // ❌ Always creates new object
// SoulState checks first:
let hasChanged = false;
for (let key in partialState) {
if (!Object.is(state[key], partialState[key])) {
hasChanged = true;
break;
}
}
if (hasChanged) {
const nextState = { ...state, ...partialState }; // ✅ Only when needed
}
Memory Management
// Single state reference
let state: T = initialState; // Only one state object in memory
// Efficient subscription cleanup
const unsubscribe = store.subscribe(selector, listener);
// Later: O(1) removal from linked list
unsubscribe(); // No memory leaks
Engine Integration Points
React Integration
// From src/react/useStore.ts
export function useStore<T, S>(
store: Store<T>,
selector: (state: T) => S,
equalityFn: (a: S, b: S) => boolean = objectIs
): S {
const getSnapshot = React.useCallback(() => selector(store.get()), [store, selector]);
const subscribe = React.useCallback(
(onStoreChange: () => void) => {
// Engine's subscribe method
const unsubscribe = store.subscribe(selector, onStoreChange, { equalityFn });
return unsubscribe;
},
[store, selector, equalityFn]
);
const value = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
return value;
}
Utility Integration
// Equality functions used by the engine
import { objectIs, shallow } from 'soulstate/utils';
// Default equality check
store.subscribe(selector, listener); // Uses objectIs
// Shallow object comparison
store.subscribe(selector, listener, { equalityFn: shallow });
Engine Characteristics
Time Complexity
- State Updates: O(k) where k = changed properties
- Subscription Management: O(1) for add/remove
- Notifications: O(n) where n = active subscriptions
Memory Footprint
- Store: O(1) additional memory
- Subscriptions: O(n) where n = active subscriptions
- No History: Single state reference only
Concurrency Safety
- Synchronous Updates: Thread-safe in JavaScript's single-threaded environment
- Microtask Batching: Prevents race conditions between updates
- Immutable State: No concurrent modification issues
Real-World Engine Behavior
Rapid Updates Scenario
// Animation frame - multiple rapid updates
const animate = () => {
store.set({ x: mouseX, y: mouseY }); // 🚫 No immediate notification
store.set({ velocity: calcVelocity() }); // 🚫 No immediate notification
store.set({ frame: frameCount++ }); // 🚫 No immediate notification
// ✅ Single notification after all updates
requestAnimationFrame(animate);
};
Form Handling Scenario
// Form submission - multiple related updates
const handleSubmit = (data) => {
store.set({ submitting: true }); // 🚫
store.set({ errors: {} }); // 🚫
store.set({ lastAttempt: Date.now() }); // 🚫
// Process data...
store.set({ data, submitting: false }); // New batch (async)
// ✅ Maximum 2 re-renders instead of 5
};
Engine Extension Points
Custom Equality Functions
// Custom comparison logic
const customEquality = (a, b) => a.id === b.id;
store.subscribe(
state => state.user,
(user, prevUser) => console.log('User changed'),
{ equalityFn: customEquality }
);
Selective Subscription Patterns
// Surgical subscriptions for optimal performance
const userName = useStore(store, state => state.user.name);
const userEmail = useStore(store, state => state.user.email);
const isActive = useStore(store, state => state.user.active);
// Each subscription independent and optimized
Engine Summary
The SoulState core engine combines intelligent change detection, microtask batching, and O(1) subscription management to deliver exceptional performance. By optimizing every phase of the update cycle, it ensures minimal overhead while maintaining perfect consistency and developer-friendly semantics.
Design Philosophy
SoulState's engine prioritizes predictability and performance. Every optimization is designed to work automatically, requiring no configuration or manual intervention from developers.