Skip to content
stroid
Docsapiuse store
Docs for v0.0.2 - current npm release. Reduce your code, reduce your stress - never your functionality.

useStore

A React hook that subscribes a component to a store. The component re-renders only when the selected value changes.

Signature

function useStore<T, R>(
  store: Store<T>,
  selector: (state: FullState<T>) => R,
  equalityFn?: (a: R, b: R) => boolean
): R

Parameters

ParameterTypeDescription
storeStore<T>The store to subscribe to, created by createStore.
selector(state) => RFunction that extracts the desired value from the store state.
equalityFn((a: R, b: R) => boolean) (optional)Custom equality function. Default: Object.is for primitives, shallow comparison for objects.

Return Value

Returns the value produced by the selector. The type is fully inferred from the selector return type.

Examples

primitives.tsx
// Selecting a primitive value
const count = useStore(store, s => s.count)
// Type: number — uses Object.is for comparison

// Selecting an object (uses shallow comparison)
const { name, email } = useStore(store, s => ({
  name: s.name,
  email: s.email,
}))

// Selecting an action (stable reference, never causes re-render)
const increment = useStore(store, s => s.increment)

// Custom equality
const items = useStore(store, s => s.items, (a, b) => 
  a.length === b.length
)

Tip

For best performance, keep selectors as focused as possible. Prefer s => s.count over s => s. Selecting the entire state object causes re-renders on every change.

Built-in Equality Functions

equality.ts
import { shallow, deep } from 'stroid'

// Shallow comparison — compares object keys one level deep
const data = useStore(store, s => ({ a: s.a, b: s.b }), shallow)

// Deep comparison — recursively compares nested structures
const nested = useStore(store, s => s.deeply.nested, deep)