Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/christianbaroni/stores/llms.txt

Use this file to discover all available pages before exploring further.

@storesjs/stores is written in TypeScript and exports all of its public types. This reference documents each exported type grouped by concern, showing the exact definition from source so you can use them confidently in your own type annotations.

Store Types

Store<S, PersistedState?, PersistReturn?>

The top-level convenience union that resolves to either a BaseStore or a PersistedStore depending on whether PersistedState is provided.
type Store<
  S,
  PersistedState extends Partial<S> = never,
  PersistReturn extends void | Promise<void> = void | Promise<void>
> = [PersistedState] extends [never]
  ? BaseStore<S>
  : PersistedStore<S, PersistedState, PersistReturn>;

BaseStore<S>

A store without persistence. Combines Zustand’s StoreApi<S> with React hook call signatures and a typed subscribe overload.
type BaseStore<S> = UseBoundStoreWithEqualityFn<StoreApi<S>> & {
  subscribe: SubscribeOverloads<S>;
};
Calling a BaseStore as a function is the React hook interface — store(), store(selector), and store(selector, equalityFn) are all valid call signatures.

PersistedStore<S, PersistedState, PersistReturn>

Extends BaseStore<S> with a persist namespace that exposes hydration, storage management, and option inspection.
type PersistedStore<
  S,
  PersistedState = Partial<S>,
  PersistReturn extends void | Promise<void> = void | Promise<void>,
> = UseStoreCallSignatures<S> & WithPersist<BaseStore<S>, PersistedState, PersistReturn>;
The persist object exposes:
persist.clearStorage
() => void
Removes the persisted entry from storage.
persist.getOptions
() => Partial<PersistOptions<S, PersistedState>>
Returns the resolved persistence options.
persist.hasHydrated
() => boolean
Returns true once the store has been hydrated from storage.
persist.onHydrate
(listener: (state: S) => void) => () => void
Registers a listener that fires when hydration begins. Returns an unsubscribe function.
persist.onFinishHydration
(listener: (state: S) => void) => () => void
Registers a listener that fires when hydration completes. Returns an unsubscribe function.
persist.rehydrate
() => Promise<void> | void
Manually triggers re-hydration from storage.
persist.setOptions
(options: Partial<PersistOptions<S, PersistedState>>) => void
Updates persistence options at runtime.
persist.hydrationPromise
() => Promise<void>
Available only on async-persisted stores. Returns a promise that resolves once hydration completes.

DerivedStore<Derived>

A read-only store produced by createDerivedStore. The setState and getInitialState methods are deprecated on this type (they throw at runtime). Adds destroy() and flushUpdates().
type DerivedStore<S> = WithFlushUpdates<ReadOnlyDerivedStore<BaseStore<S>>>;
destroy
() => void
Destroys the derived store and its internal subscriptions. Usually unnecessary since derived stores self-clean when all subscribers leave, unless keepAlive: true was specified.
flushUpdates
() => void
Immediately flushes any pending debounced updates. Only applicable to derived stores created with the debounce option.

OptionallyPersistedStore<S, PersistedState, PersistReturn>

Used by store creators that accept optional persistence configuration. The persist namespace is present only when a storageKey is supplied.
type OptionallyPersistedStore<S, PersistedState, PersistReturn extends void | Promise<void> = void> =
  UseStoreCallSignatures<S> &
  Omit<BaseStore<S>, 'setState'> & {
    persist?: PersistedStore<S, PersistedState, PersistReturn>['persist'];
    setState(update: SetPartial<S>, replace?: false): PersistReturn;
    setState(update: SetFull<S>, replace: true): PersistReturn;
  };

StoreActions<Store>

Picks all function-typed keys from a store’s state type. This is the return type of createStoreActions.
type StoreActions<Store extends StoreApi<unknown>> =
  Pick<InferStoreState<Store>, FunctionKeys<InferStoreState<Store>>>;

InferStoreState<Store>

Extracts the state type S from any store that has a getState method.
type InferStoreState<Store> = Store extends { getState: () => infer T } ? T : never;

InferPersistedState<Store>

Extracts the PersistedState type from a persisted store. Returns never for non-persisted stores.
type InferPersistedState<PersistedStore> =
  PersistedStore extends Store<infer _, infer PersistedState>
    ? PersistedState
    : never;

InferSetStateReturn<Store>

Extracts the return type of a store’s setState method — void for synchronous stores, Promise<void> for async-persisted stores.
type InferSetStateReturn<Store> =
  Store extends { setState(...args: SetStateArgs<infer S>): infer R }
    ? R
    : void;

Persistence Types

PersistConfig<S, PersistedState, PersistReturn>

All options accepted when configuring persistence for a store.
type PersistConfig<
  S,
  PersistedState extends Partial<S> = Partial<S>,
  PersistReturn = void
> = {
  storageKey: string;
  version?: number;
  partialize?: (state: Readonly<S>) => PersistedState;
  merge?: (persistedState: PersistedState | undefined, currentState: S) => S;
  migrate?: (persistedState: PersistedState, version: number) => PersistedState | Promise<PersistedState>;
  onRehydrateStorage?: (state: S) => ((state?: S, error?: unknown) => void) | void;
  serializer?: (storageValue: StorageValue<PersistedState>) => string;
  deserializer?: (serializedState: unknown) => StorageValue<PersistedState>;
  storage?: PersistReturn extends Promise<unknown> ? AsyncStorageInterface : SyncStorageInterface;
  persistThrottleMs?: PersistReturn extends Promise<unknown> ? undefined : number;
};
storageKey
string
required
The unique key under which the store’s state is persisted.
version
number
default:"0"
Schema version number. When the persisted version differs from this value, migrate is called.
partialize
(state: Readonly<S>) => PersistedState
Returns the subset of state to persist. Defaults to the entire state.
merge
(persisted, current) => S
Custom merge strategy for hydration. Defaults to a shallow merge.
migrate
(persisted, version) => PersistedState | Promise<PersistedState>
Called when the stored version does not match version.
onRehydrateStorage
(state: S) => callback | void
A function called before hydration. May return a callback that is invoked after hydration completes or when an error occurs.
serializer
(storageValue) => string
Custom serializer. Defaults to the storage adapter’s serializer, then JSON.stringify.
deserializer
(serializedState) => StorageValue<PersistedState>
Custom deserializer. Defaults to the storage adapter’s deserializer, then JSON.parse.
storage
SyncStorageInterface | AsyncStorageInterface
Override the global storage adapter for this specific store.
persistThrottleMs
number
Throttle rate for write operations in milliseconds. Not applicable to async stores. Defaults to 3 s on iOS and 5 s on Android.

StorageValue<S, HideSyncMetadata?>

The shape of the value stored in and read from storage by the persistence layer.
type StorageValue<S, HideSyncMetadata extends boolean = false> = HideSyncMetadata extends true
  ? {
      state: S;
      version?: number;
    }
  : {
      state: S;
      syncMetadata?: { origin?: string; timestamp?: number; fields?: Record<string, number> };
      version?: number;
    };
Pass StorageValue<PersistedState> (with HideSyncMetadata defaulting to false) in custom serializer and deserializer functions to get the full value including optional sync metadata. When HideSyncMetadata is true, the syncMetadata field is omitted from the type — useful when you know your store does not use sync.

SyncStorageInterface<SerializedState>

Contract for synchronous storage adapters such as localStorage or MMKV.
type SyncStorageInterface<SerializedState = unknown> = {
  readonly async?: false;
  deserializer?<PersistedState>(serializedState: SerializedState): StorageValue<PersistedState>;
  serializer?<PersistedState>(storageValue: StorageValue<PersistedState>): SerializedState;
  clearAll(): void;
  contains(key: string): boolean;
  delete(key: string): void;
  get(key: string): SerializedState | undefined;
  getAllKeys(): string[];
  set(key: string, value: SerializedState): void;
};

AsyncStorageInterface<SerializedState>

Contract for asynchronous storage adapters such as Chrome extension storage.
type AsyncStorageInterface<SerializedState = unknown> = {
  readonly async: true;
  deserializer?<PersistedState>(serializedState: SerializedState): StorageValue<PersistedState>;
  serializer?<PersistedState>(storageValue: StorageValue<PersistedState>): SerializedState;
  clearAll(): Promise<void>;
  contains(key: string): Promise<boolean>;
  delete(key: string): Promise<void>;
  get(key: string): Promise<SerializedState | undefined>;
  getAllKeys(): Promise<string[]>;
  set(key: string, value: SerializedState): Promise<void>;
};
The async: true discriminant allows the framework to detect at runtime whether a storage adapter is synchronous or asynchronous and adjust the setState return type accordingly.

Query Store Types

QueryStoreConfig<TQueryFnData, TParams, TData, CustomState>

Full configuration accepted by createQueryStore. See configureStores for the subset of these fields that can be set as global defaults via queryStoreDefaults. Key fields:
fetcher
(params: TParams, abortController: AbortController | null) => TQueryFnData | Promise<TQueryFnData>
required
The async function responsible for loading remote data.
params
QueryStoreParams
Static, reactive, or queryParam-wrapped parameters forwarded to fetcher.
staleTime
number | ReactiveParam<number, S>
default:"time.minutes(2)"
How long fetched data is considered fresh before background refetching may occur.
cacheTime
number | ((params: TParams) => number)
default:"time.days(7)"
How long a cache entry is retained before pruning.
enabled
boolean | ReactiveParam<boolean, S>
default:"true"
Whether the store actively fetches. Can be a static boolean or a reactive getter.
transform
(data: TQueryFnData, params: TParams) => TData
Transforms raw fetcher output into the shape stored in the cache. Required when TData differs from TQueryFnData.
onFetched
(info: OnFetchedParams) => void
Callback invoked after every successful fetch.
onError
(error: Error, retryCount: number) => void
Callback invoked after every failed fetch attempt.
setData
(info: SetDataParams) => void
Overrides the default behaviour of writing fetched data into the internal query cache.
maxRetries
number
default:"5"
Maximum number of automatic retry attempts after a fetch failure.
retryDelay
number | ((retryCount: number, error: Error) => number)
Delay between retry attempts. Defaults to exponential backoff.
keepPreviousData
boolean
default:"false"
When true, getData() returns stale data while a new fetch is in flight.
disableCache
boolean
default:"false"
When true, fetched data is not written to the internal cache.
disableAutoRefetching
boolean
default:"false"
When true, stale data is not automatically refreshed in the background.
abortInterruptedFetches
boolean
default:"true"
When true, in-flight fetches are aborted when parameters change or all subscribers unmount.
paramChangeThrottle
false | number | DebounceOptions
default:"false"
Delay before triggering a fetch in response to parameter changes.
debugMode
boolean
default:"false"
Enables verbose console logging for this store.
suppressStaleTimeWarning
boolean
default:"false"
Suppresses the development warning emitted when staleTime is shorter than minStaleTime.

QueryStoreState<TData, TParams, CustomState>

The full runtime state managed by a query store. Includes all internal state keys plus any custom state fields.
type QueryStoreState<TData, TParams extends Record<string, unknown>, CustomState = unknown> =
  QueryStoreInternalState<TData, TParams> & CustomState;
Internal state fields:
status
QueryStatus
Current fetch status: 'idle', 'loading', 'success', or 'error'.
enabled
boolean
Whether the store is actively fetching.
error
Error | null
The most recent fetch error, or null.
lastFetchedAt
number | null
Timestamp of the last successful fetch.
queryCache
Record<string, CacheEntry<TData> | undefined>
Internal map of cache entries keyed by generated query key strings.
queryKey
string
The deterministic query key built from current parameters.
fetch
(params?, options?) => Promise<TData | null>
Imperatively trigger a fetch. See FetchOptions for available options.
getData
(paramsOrQueryKey?) => CacheEntry<TData>['data']
Returns cached data for the given parameters or query key.
getCacheEntry
(paramsOrQueryKey?) => CacheEntry<TData> | null
Returns the full cache entry (data + metadata) for the given key.
getStatus
(statusKey?) => QueryStatusInfo | boolean
Returns expanded status flags. Pass a keyof QueryStatusInfo to retrieve a single flag.
isStale
(override?: number) => boolean
Returns true when the current data has exceeded staleTime.
isDataExpired
(override?: number) => boolean
Returns true when the current cache entry has exceeded cacheTime.
reset
(resetStoreState?: boolean) => void
Tears down param subscriptions and timers. Optionally resets all state.

QueryStatus

type QueryStatus = 'idle' | 'loading' | 'success' | 'error';
The set of possible fetch statuses. Use the QueryStatuses constants object to avoid raw string comparisons.

QueryStatusInfo

type QueryStatusInfo = {
  isError: boolean;
  isIdle: boolean;
  isInitialLoad: boolean;
  isLoading: boolean;
  isSuccess: boolean;
};
Expanded boolean flags returned by getStatus().

CacheEntry<T>

A cache entry storing fetched data alongside fetch metadata and optional error information.
type CacheEntry<T> = {
  cacheTime: number;
  data: T | null;
} & (
  | {
      errorInfo: { error: Error; lastFailedAt: number; retryCount: number };
      lastFetchedAt: null;
    }
  | {
      errorInfo: { error: Error; lastFailedAt: number; retryCount: number } | null;
      lastFetchedAt: number;
    }
);

FetchOptions

Options accepted by the fetch method on a query store’s state.
force
boolean
default:"false"
Forces a fetch even when fresh data is available in the cache.
staleTime
number
Overrides the store’s staleTime for this specific fetch call.
cacheTime
number
Overrides the store’s cacheTime for the data fetched in this call.
skipStoreUpdates
boolean | 'withCache'
default:"false"
When true, the fetch runs silently without updating store state. When 'withCache', the result is written to the cache but store state is otherwise untouched.
updateQueryKey
boolean
Whether to update the store’s queryKey to reflect the params used in this fetch. Defaults to false for manual fetches.
throwOnError
boolean
default:"false"
When true, the returned promise rejects on fetch failure instead of updating store error state silently.

QueryParam<T, State>, ReactiveParam<T, State>, QueryParamConfig<T, State>

// A value derived reactively from other stores
type ReactiveParam<T, State> = ($: DeriveGetter, store: StoreApi<State>) => T;

// A queryParam(...) wrapper with custom key behaviour
type QueryParamConfig<T, State> = {
  readonly key: QueryParamKey<T>;
  readonly value: NonFunction<T> | ReactiveParam<T, State>;
};

// Any valid param form: static value, reactive getter, or key-configured wrapper
type QueryParam<T, State> =
  | NonFunction<T>
  | ReactiveParam<T, State>
  | QueryParamConfig<T, State>;

// Controls how the param appears in the query key
type QueryParamKey<T> = false | ((value: T) => unknown);

Sync Types

FieldMetadata

Metadata recorded for each synced field write. A tuple of the write timestamp and the originating session ID.
type FieldMetadata = readonly [timestamp: number, sessionId: string];

SyncStateKey<T>

Extracts only the non-function keys from a store state type T. These are the keys that can be included in SyncConfig.fields and used as sync targets.
type SyncStateKey<T extends Record<string, unknown>> = Extract<
  {
    [K in keyof T]-?: T[K] extends UnknownFunction ? never : K;
  }[keyof T],
  string
>;

SyncValues<T>

A partial object of the non-function state keys of T. This is the type of values in a SyncUpdate.
type SyncValues<T extends Record<string, unknown>> = Partial<T> & {
  [K in SyncStateKey<T>]?: T[K];
};

SyncConfig<T>

Options for enabling cross-client sync on a store.
type SyncConfig<T extends Record<string, unknown>> = {
  key?: string;
  fields?: ReadonlyArray<SyncStateKey<T>>;
  engine?: SyncEngine;
  merge?: { [K in SyncStateKey<T>]?: SyncMergeFn<T[K], T> };
  injectStorageMetadata?: boolean;
};
key
string
Identifier shared across clients to target the same store. Required when the store is not persisted (no storageKey to fall back on).
fields
ReadonlyArray<SyncStateKey<T>>
The specific state keys to synchronize. Defaults to all non-function properties.
engine
SyncEngine
Override the global sync engine for this store.
merge
object
Per-field merge functions for conflict resolution. Use with caution.
injectStorageMetadata
boolean
default:"false"
When true, sync metadata is embedded in the storage payload. Required for engines that use storage writes as their transport (e.g. chrome.storage).

SyncEngine interface

Interface for pluggable multi-client synchronization.
interface SyncEngine {
  readonly sessionId: string;
  readonly injectStorageMetadata?: boolean;
  register: {
    <T extends Record<string, unknown>>(registration: SyncRegistration<T>): SyncHandle<T>;
    (registration: SyncRegistration<Record<string, unknown>>): SyncHandle<Record<string, unknown>>;
  };
}
sessionId
string
A unique identifier for this client session, used for conflict resolution and self-update filtering.
injectStorageMetadata
boolean | undefined
When true, the engine requires sync metadata to be embedded in persisted storage values.
register
(registration: SyncRegistration<T>) => SyncHandle<T>
Connects a store to the sync system. Returns a SyncHandle to manage the sync lifecycle.

SyncHandle<T> interface

Returned by SyncEngine.register(). Controls the lifecycle of a synced store.
interface SyncHandle<T extends Record<string, unknown>> {
  destroy: () => void;
  publish: ((update: SyncUpdate<T>) => void) | null;
  hydrated?: () => boolean;
  onFirstSubscribe?: () => void;
  onLastUnsubscribe?: () => void;
  onHydrated?: (callback: () => void) => void;
}
destroy
() => void
Permanently removes this store from the sync engine.
publish
((update: SyncUpdate<T>) => void) | null
Broadcasts a state update to other clients. null for engines where publishing is implicit (e.g. chrome.storage).
hydrated
() => boolean
Returns true once the store has received its initial state from the engine.
onFirstSubscribe
() => void
Called when the store’s subscriber count goes from 0 to 1. Use for lazy resource acquisition (e.g. opening a WebSocket).
onLastUnsubscribe
() => void
Called when the store’s subscriber count drops to 0. Use for resource cleanup.
onHydrated
(callback: () => void) => void
Registers a one-time callback fired when hydration completes.

SyncRegistration<T>

Passed to SyncEngine.register() to describe the store being registered.
type SyncRegistration<T extends Record<string, unknown>> = {
  key: string;
  fields: ReadonlyArray<SyncStateKey<T>>;
  getState: () => T;
  apply: (update: SyncUpdate<T>) => void;
};

SyncUpdate<T>

The payload broadcast between clients when state changes.
type SyncUpdate<T extends Record<string, unknown>> = {
  replace: boolean;
  sessionId: string;
  timestamp: number;
  values: SyncValues<T>;
};

Derive Types

DeriveGetter

The $ argument received inside a createDerivedStore callback. Two overloads are available:
type DeriveGetter = {
  // Proxy-based: access any property and the accessed paths become dependencies
  <Store extends StoreApi<InferStoreState<Store>>>(store: Store): InferStoreState<Store>;

  // Selector-based: subscribe to the result of a selector
  <Store extends StoreApi<InferStoreState<Store>>, Selected>(
    store: Store,
    selector: Selector<InferStoreState<Store>, Selected>,
    equalityFn?: EqualityFn<Selected>
  ): Selected;
};

DeriveOptions<Derived>

Configuration for createDerivedStore. Can be passed as a plain equality function or as a config object.
type DeriveOptions<DerivedState = unknown> =
  | EqualityFn<DerivedState>
  | {
      debounce?: number | DebounceOptions;
      debugMode?: boolean | 'verbose';
      equalityFn?: EqualityFn<DerivedState>;
      keepAlive?: boolean;
      lockDependencies?: boolean;
    };
debounce
number | DebounceOptions
Adds a debounce delay before the derive function re-runs when dependencies change. Accepts a plain number (ms) or a full DebounceOptions object for leading/trailing/maxWait control.
debugMode
boolean | 'verbose'
default:"false"
When true, logs dependency subscriptions on the first derivation run. When 'verbose', logs on every run.
equalityFn
EqualityFn<DerivedState>
default:"Object.is"
Custom equality check to suppress downstream updates when the derived value has not meaningfully changed.
keepAlive
boolean
default:"false"
When true, the derived store never self-destructs even when subscriber count drops to zero.
lockDependencies
boolean
default:"false"
When true, the dependency graph is fixed after the first derivation. Subscriptions are established once and reused, avoiding subscription churn. Safe when all $ calls are unconditional and top-level.

Hook Types

ListenHandle

type ListenHandle = {
  isActive: boolean;
  resubscribe: (options?: ResubscribeOptions) => void;
  unsubscribe: () => void;
};
Returned by useListen as a ref. See the Hooks reference for full usage details.

UseListenOptions<Selected>

type UseListenOptions<Selected> = {
  enabled?: boolean;
  equalityFn?: EqualityFn<Selected>;
  fireImmediately?: boolean;
  debugMode?: boolean;
};
Options accepted by useListen. See the Hooks reference for default values and reactive behaviour notes.

Build docs developers (and LLMs) love