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

Computed Values

stroid does not ship a special “computed” primitive. Derive values in selectors or compute them once and store them yourself. This keeps the core small and predictable.

Derive in selectors

Most cases are covered by selectors passed to useStore. The selector runs only when the referenced slice changes.

CartSummary.tsx
import { useStore } from 'stroid'

function CartSummary() {
  const { total, count } = useStore('cart', (s) => ({
    count: s.items.length,
    total: s.items.reduce((sum, i) => sum + i.price, 0),
  }))

  return (
    <div>
      <p>Items: {count}</p>
      <p>Total: ${total.toFixed(2)}</p>
    </div>
  )
}

Precompute and store

If you need the derived value elsewhere (e.g., persistence, cross-tab sync), compute it inside setStore and store it alongside the source data.

cart-store.ts
import { createStore, setStore } from 'stroid'

createStore('cart', { items: [], total: 0 })

export function addItem(item: Item) {
  setStore('cart', (d) => {
    d.items.push(item)
    d.total = d.items.reduce((sum, i) => sum + i.price, 0)
  })
}

Tip

Keep selectors small and pure. If a derived value is expensive, memoize it in userland withuseMemo or store it during updates as shown above.