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

useStore & Selectors

useStore(name, selector?) subscribes a component to a named store. The selector keeps re-renders minimal by choosing only what the component needs.

Basic Selector

Component.tsx
import { useStore } from 'stroid'

function TodoCount() {
  // Only re-renders when todos length changes
  const count = useStore('todos', (s) => s.items.length)
  return <span>Todos: {count}</span>
}

function TodoList() {
  const todos = useStore('todos', (s) => s.items)
  return <ul>{todos.map((t) => <li key={t.id}>{t.text}</li>)}</ul>
}

Tip

Always select the smallest piece of state your component needs. Selecting the entire store object will cause re-renders on every state change.

Selecting multiple values

Return an object to select more than one field. Objects use shallow comparison by default.

multiple.tsx
function TodoHeader() {
  const { count, filter } = useStore('todos', (s) => ({
    count: s.items.length,
    filter: s.filter,
  }))

  return <h1>{filter} ({count})</h1>
}

Custom Equality

Pass a custom equality function as the third argument when needed.

equality.tsx
import { shallow } from 'stroid'

// Shallow comparison (default for objects)
const data = useStore('settings', (s) => ({ theme: s.theme, lang: s.language }), shallow)

// Custom comparison
const custom = useStore('todos', (s) => s.items, (a, b) =>
  a.length === b.length && a.every((item, i) => item.id === b[i].id)
)

Outside React

For non-React code, call getStore andsetStore directly.

outside.ts
import { getStore, setStore } from 'stroid'

const todos = getStore('todos') // snapshot

setStore('todos', (d) => {
  d.items.push({ id: Date.now(), text: 'Write docs', done: false })
})