Skip to main content

React API

SoulState provides a first-class React integration layer designed for surgical re-renders and concurrent safety.

useStore

The primary hook for subscribing to store state in React components.

Signature

function useStore<T, S>(
store: StoreApi<T>,
selector: (state: T) => S,
equalityFn?: (a: S, b: S) => boolean
): S;

Behavior

  1. Surgical Dependency Tracking: During the first render, useStore runs your selector with a Tracking Proxy. It detects which top-level keys you accessed (e.g., user) and registers the component as a granular listener for those keys.
  2. Irrelevant Update Elimination: If a part of the state changes that your selector did not access, the component will not re-render, and the selector will not even re-execute.
  3. Concurrent Safety: Built on useSyncExternalStore, ensuring no "tearing" occurs during React's concurrent rendering.
import { useStore } from 'soulstate/react';

function Profile() {
// Only re-renders if 'user.name' or 'user' key changes
const name = useStore(store, s => s.user.name);
return <h1>{name}</h1>;
}

Provider

A context-based provider for distributing stores through the component tree. This is useful for scoped stores (e.g., one store per workspace or dashboard tab).

Usage

import { Provider } from 'soulstate/react';

function App() {
const [myStore] = useState(() => createStore(initialState));

return (
<Provider store={myStore}>
<Dashboard />
</Provider>
);
}

useStoreContext

Access the store instance provided by the nearest Provider.

import { useStoreContext, useStore } from 'soulstate/react';

function ScopedComponent() {
const store = useStoreContext();
const data = useStore(store, s => s.data);

return <div>{data}</div>;
}

useShallow

A specialized hook for selecting multiple properties while maintaining stable references.

import { useShallow } from 'soulstate/react';

function UserCard() {
// Re-renders only if name or email changes
const { name, email } = useShallow(
store,
s => ({ name: s.user.name, email: s.user.email })
);

return <div>{name} ({email})</div>;
}

Concurrent Mode Ready

SoulState is fully compatible with React 18+ Concurrent Mode and Strict Mode. It handles "double-mount" behaviors in development without leaking subscriptions or creating duplicate listeners.