import { useStore } from 'zustand' import { defaultKeyStats, type KeyStats, type StatsStore } from './stats-store' import type { EngineStore } from './store' import type { SourceState } from './types' /** * Subscribe to a single engine slice by key. * The component re-renders only when that slice changes. * * @example * const slice = useEngineSlice(engine, 'user') * if (slice?.isLoading) return * return
{slice?.data?.name}
*/ export function useEngineSlice( engine: { store: EngineStore }, key: string, ): SourceState | undefined { return useStore(engine.store, (state) => state.slices[key]) as | SourceState | undefined } /** * Subscribe to the performance stats for a single key. * The component re-renders only when that key's stats change. * Returns zeroed stats if the key has not been registered yet. * * @example * const stats = useEngineStats(engine, 'user') * return
API calls: {stats.apiFetchCount} | Cache hits: {stats.cacheHitCount}
*/ export function useEngineStats( engine: { statsStore: StatsStore }, key: string, ): KeyStats { return useStore(engine.statsStore, (state) => state[key] ?? defaultKeyStats()) }