Skip to content

Advanced

Beyond the basic effect, the library provides advanced tools for managing effects lifecycle and subscribing to changes in different ways.

effectScope creates a scope for multiple effects, allowing you to stop them all at once. This is useful when you need to manage multiple subscriptions together and dispose of them as a group.

import { signal, effect, effectScope } from '@nano_kit/store'
const $firstName = signal('John')
const $lastName = signal('Doe')
const $age = signal(30)
const stop = effectScope(() => {
effect(() => {
console.log('Name:', `${$firstName()} ${$lastName()}`)
})
effect(() => {
console.log('Age:', $age())
})
})
/* All effects in the scope are stopped */
stop()

onMountEffect runs an effect only when a mountable signal becomes active. This combines lifecycle management with reactive effects.

import { signal, mountable, onMountEffect } from '@nano_kit/store'
const $user = mountable(signal(null))
const $userId = signal(1)
/* Effect runs only when $user is mounted */
onMountEffect($user, () => {
console.log('Fetching user:', $userId())
/* Effect re-runs when $userId changes */
})

onMountEffectScope runs an entire effect scope on mount:

import { signal, mountable, onMountEffectScope, effect } from '@nano_kit/store'
const $data = mountable(signal(null))
const $status = signal('idle')
onMountEffectScope($data, () => {
effect(() => console.log('Data changed:', $data()))
effect(() => console.log('Status:', $status()))
})

These functions provide different ways to react to signal changes:

subscribe - Calls the callback immediately and on every change. Triggers mount if the accessor is mountable.

import { subscribe } from '@nano_kit/store'
const stop = subscribe($count, (value) => {
console.log('Current value:', value)
})
/* Called immediately with current value, then on every change */

listen - Calls the callback only on changes, skipping the initial call. Triggers mount.

import { listen } from '@nano_kit/store'
const stop = listen($count, (value) => {
console.log('Changed to:', value)
})
/* Called only when $count changes, not immediately */

observe - Calls the callback only on changes, without triggering mount. Useful for passive observation.

import { observe } from '@nano_kit/store'
const $data = mountable(signal(0))
const stop = observe($data, (value) => {
console.log('Observed:', value)
})
/* $data remains unmounted until something else mounts it */

subscribeAny - Subscribes to a signal or calls the callback immediately with a plain value. Useful when you have a value that may or may not be reactive.

import { signal, subscribeAny } from '@nano_kit/store'
const $count = signal(0)
/* Works with a signal */
subscribeAny($count, (value) => console.log('Value:', value))
/* Works with a plain value */
subscribeAny(42, (value) => console.log('Value:', value))
/* Calls callback immediately with 42 */

When working with objects and arrays, the library provides tools to create reactive child signals for individual properties or elements. This enables fine-grained reactivity while keeping your code organized.

record wraps an object signal and exposes its properties as individual signals. Each property becomes accessible through a $-prefixed accessor.

import { signal, record } from '@nano_kit/store'
const $user = signal({ name: 'Dan', age: 30 })
const $userRecord = record($user)
/* Access properties as signals */
console.log($userRecord.$name()) /* Dan */
console.log($userRecord.$age()) /* 30 */
/* Update individual properties */
$userRecord.$name('Alice')
console.log($user()) /* { name: 'Alice', age: 30 } */

record can also wrap plain objects:

const $user = record({ name: 'Dan', age: 30 })
$user.$name('Bob')

deepRecord recursively wraps nested objects, providing signals for properties at any depth.

import { deepRecord } from '@nano_kit/store'
const $user = deepRecord({
name: 'Dan',
address: {
city: 'Batumi',
country: 'Georgia'
}
})
/* Access nested properties */
console.log($user.$address.$city()) /* Batumi */
/* Update nested properties */
$user.$address.$city('Tbilisi')

For arrays, use atIndex to create a signal for a specific element. The index can be static or dynamic.

import { signal, atIndex } from '@nano_kit/store'
const $users = signal(['Dan', 'John', 'Alice'])
const $firstUser = atIndex($users, 0)
console.log($firstUser()) /* Dan */
/* Update through child signal */
$firstUser('Bob')
console.log($users()) /* ['Bob', 'John', 'Alice'] */

Dynamic indexes:

const $index = signal(1)
const $user = atIndex($users, $index)
console.log($user()) /* John */
$index(2)
console.log($user()) /* Alice */

Finding elements by predicate with atFoundIndex:

import { signal, atFoundIndex } from '@nano_kit/store'
const $users = signal([
{ id: 1, name: 'Dan' },
{ id: 2, name: 'John' },
{ id: 3, name: 'Alice' }
])
/* Select user with id 2 */
const $targetUser = atFoundIndex($users, (user) => user.id === 2)
console.log($targetUser()) /* { id: 2, name: 'John' } */

Additional array helpers:

  • updateArray($array, fn) - update the array signal using a function
  • push($array, ...values) - add elements to the end
  • pop($array) - remove and return the last element
  • shift($array) - remove and return the first element
  • unshift($array, ...values) - add elements to the start
  • setIndex($array, index, value) - update element at index
  • deleteIndex($array, index) - remove element at index

atKey creates a signal for a specific key in an object. Works with both static and dynamic keys.

import { signal, atKey } from '@nano_kit/store'
const $userMap = signal({
2: 'Dan',
4: 'John',
6: 'Alice'
})
const $user4 = atKey($userMap, 4)
console.log($user4()) /* John */
$user4('Bob')
console.log($userMap()) /* { 2: 'Dan', 4: 'Bob', 6: 'Alice' } */

Dynamic keys:

const $userId = signal(4)
const $user = atKey($userMap, $userId)
$userId(6)
console.log($user()) /* Alice */

Additional object helpers:

  • setKey($object, key, value) - set a property value
  • deleteKey($object, key) - remove a property

SignalsMap is a Map whose values are reactive: every value lives in a signal of its own, and the signals never leave the map. It is a class created with new, where get reads a value without tracking, $get reads it and tracks it, and set, delete, clear, has, keys and size work as they do on a Map.

import { SignalsMap, effect } from '@nano_kit/store'
interface User {
id: number
name: string
}
const users = new SignalsMap<number, User>()
/* Set entry */
users.set(1, { id: 1, name: 'Dan' })
/* Get entry reactively */
effect(() => {
console.log('User:', users.$get(1))
})
/* Update entry with a reducer, as with a writable signal */
users.set(1, user => user && { ...user, name: 'Alice' })
/* Get entry without tracking */
users.get(1)
/* Delete entry */
users.delete(1)
/* Clear all */
users.clear()

A reader of a key that is in the map runs again only when its value changes, not when other keys are set. A reader of a missing key runs again when a key is added or removed, so it gets the value as soon as the key is set.

IndexedSignalsMap adds $index, a computed list of the keys: it changes when a key is added or removed, not when a value is set. $index also stands for the whole map in the lifecycle: mark it mountable right after the map is created, and every reader of the map mounts it, the readers of $get included.

import { IndexedSignalsMap, mountable, onMount, effect } from '@nano_kit/store'
const users = new IndexedSignalsMap<number, User>()
/* Mark the index mountable before anything reads the map */
onMount(mountable(users.$index), () => {
/* Runs when the first reader of the map appears */
const socket = new WebSocket('wss://example.com/users')
socket.onmessage = (event) => {
const user: User = JSON.parse(event.data)
users.set(user.id, user)
}
return () => socket.close()
})
/* Runs again when a key is added or removed, not when a value is set */
effect(() => {
console.log('User ids:', users.$index())
})
/* Runs again when user 1 changes, and keeps the map mounted as well */
effect(() => {
console.log('User 1:', users.$get(1))
})

Functional operators (fops) are pure functions that combine accessors and plain values. Every operator checks its operands: with an accessor among them the result is an accessor, and with none it is the plain value, so a binding made of static values costs no effect. Unlike computed, a returned accessor does not memoize: it recalculates on every access. For memoization, wrap it in computed.

import { type Signalish, signal, is } from '@nano_kit/store'
const $variant = signal('primary')
/* Accessor<boolean>: an accessor is among the operands */
const $isPrimary = is($variant, 'primary')
/* boolean: every operand is static */
const isPrimary = is('primary', 'primary')
/* Signalish<boolean>: the operand may turn out either way */
function isPrimaryVariant(variant: Signalish<string>) {
return is(variant, 'primary')
}

The Fop type describes the result of an operator: an accessor when an operand is an accessor, the plain value when none can be, and Signalish of the value when an operand may be either.

import { signal, or, and, not, some, every } from '@nano_kit/store'
const $isAdmin = signal(false)
const $isModerator = signal(true)
/* OR: returns first truthy value */
const $hasPermissions = or($isAdmin, $isModerator)
/* AND: returns last value if all truthy */
const $canEdit = and($isAdmin, $hasPermissions)
/* NOT: logical negation */
const $isGuest = not($hasPermissions)
/* SOME: first truthy from multiple values */
const $primaryRole = some($isAdmin, $isModerator, 'guest')
/* EVERY: last value if all truthy, otherwise first falsy */
const $allChecks = every($isAdmin, $isModerator, $hasPermissions)
import { signal, is, isNot, gt, gte, lt, lte } from '@nano_kit/store'
const $age = signal(25)
const $limit = signal(18)
/* Strict equality */
const $isAdult = gte($age, 18)
/* Strict inequality */
const $notEqual = isNot($age, $limit)
/* Comparisons */
const $olderThanLimit = gt($age, $limit)
const $atLeastLimit = gte($age, $limit)
const $youngerThanLimit = lt($age, $limit)
const $atMostLimit = lte($age, $limit)
import { signal, when } from '@nano_kit/store'
const $isLoggedIn = signal(true)
const $username = signal('Alice')
/* Ternary: condition ? then : otherwise */
const $greeting = when(
$isLoggedIn,
() => `Hello, ${$username()}`,
'Please log in'
)
console.log($greeting()) /* "Hello, Alice" */

pick looks a value up in a collection by key. The collection is an object or an array, and both it and the key can be static or accessors. An empty key (null or undefined) picks undefined, which suits an optional prop.

import { signal, pick } from '@nano_kit/store'
const styles = {
primary: 'button_primary',
secondary: 'button_secondary'
}
const $variant = signal<'primary' | 'secondary'>('primary')
const $className = pick(styles, $variant)
console.log($className()) /* "button_primary" */
$variant('secondary')
console.log($className()) /* "button_secondary" */
/* Static operands give the value itself */
pick(styles, 'primary') /* "button_primary" */

text is a template tag that builds a string from a template literal. The values in it are strings, numbers, booleans or bigints, static or accessors, and an empty value (null or undefined) adds nothing.

import { signal, text } from '@nano_kit/store'
const $name = signal('Dan')
const $greeting = text`Hello, ${$name}!`
console.log($greeting()) /* "Hello, Dan!" */
$name('Alice')
console.log($greeting()) /* "Hello, Alice!" */
/* Static values give the string itself */
text`Step ${1} of ${3}` /* "Step 1 of 3" */

Since fops don’t cache results, wrap them in computed for expensive operations:

import { signal, computed, and, gt } from '@nano_kit/store'
const $age = signal(25)
const $hasLicense = signal(true)
/* Without memoization - recalculates on every access */
const $canDrive = and(gt($age, 18), $hasLicense)
/* With memoization - caches until dependencies change */
const $canDriveCached = computed($canDrive)

A codec is a small universal interface for converting values from one representation to another and back.

interface Codec<D, E> {
encode(value: D): E
decode(value: E | null): D | null
}

Codecs are used by storage, hydration, and other APIs that need to serialize values without owning the serialization format.

import { JsonCodec, BooleanCodec, NoopCodec, isCodec } from '@nano_kit/store'
JsonCodec.encode({ count: 1 }) /* '{"count":1}' */
JsonCodec.decode<{ count: number }>('{"count":1}') /* { count: 1 } */
BooleanCodec.encode(true) /* '1' */
BooleanCodec.decode('0') /* false */
NoopCodec.encode('value') /* 'value' */
NoopCodec.decode('value') /* 'value' */
isCodec(JsonCodec) /* true */

Built-in codecs:

  • JsonCodec - encodes values with JSON.stringify and decodes with JSON.parse
  • BooleanCodec - encodes booleans as '1' / '0'
  • NoopCodec - passes values through unchanged

The library provides a set of utility functions for common tasks like rate limiting, value extraction, type checking, and working with signal properties.

resolved unwraps a promise accessor into a [$result, $error, $pending] tuple of signals. Stale data is preserved while a new promise is pending.

import { signal, computed, resolved } from '@nano_kit/store'
function getPosition(options?: PositionOptions) {
return new Promise<GeolocationPosition>((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options)
})
}
const $highAccuracy = signal(false)
const [$position, $error, $pending] = resolved(
() => getPosition({ enableHighAccuracy: $highAccuracy() })
)

A source value that is not a promise becomes the result as it is, a falsy one included, so an empty state is expressed by the type itself, for example User | null.

import { signal, resolved } from '@nano_kit/store'
const $userId = signal<number | null>(null)
const [$user] = resolved(() => {
const id = $userId()
/* The result is null until there is a user to fetch */
return id === null ? null : fetchUser(id)
})

Each promise from the source is attached as a task, so waitTasks of any of the three signals waits until it settles. A signal of the tuple links the source on its first read, so read or mount it before waiting.

pace creates a rate-limited accessor from another accessor. Wrap it with computed to memoize the paced value and avoid extra effect runs while the rate limiter is waiting.

import { signal, computed, pace, effect, debounce } from '@nano_kit/store'
const $search = signal('')
const $searchPaced = computed(pace($search, debounce(300)))
effect(() => {
console.log('Search:', $searchPaced())
})
$search('a')
$search('ab')
$search('abc')
/* Only logs "abc" after debounce completes */

paced creates a proxy signal that updates the original signal using a rate limiter. This allows you to control how frequently a signal propagates updates while keeping immediate local updates. The proxy signal updates instantly, but the original signal updates only after the rate limiter allows it.

import { signal, paced, effect, debounce } from '@nano_kit/store'
const $search = signal('')
const $searchPaced = paced($search, debounce(300))
effect(() => {
console.log('Search:', $search())
})
/* $searchPaced updates immediately, $search updates after 300ms */
$searchPaced('a')
$searchPaced('ab')
$searchPaced('abc')
/* Only logs "abc" after debounce completes */

debounce and throttle are rate limiters that work with pace and paced:

debounce delays updates until after a specified time has passed since the last change. Useful for expensive operations like search queries or API calls.

import { signal, paced, debounce } from '@nano_kit/store'
const $input = signal('')
const $debouncedInput = paced($input, debounce(300))
/* Only the last value within 300ms window propagates to $input */

throttle limits updates to once per time interval. First update executes immediately, subsequent updates are queued until the interval elapses.

import { signal, paced, throttle } from '@nano_kit/store'
const $scrollY = signal(0)
const $throttledScroll = paced($scrollY, throttle(100))
/* Updates $scrollY at most once per 100ms */

You can also use debounce and throttle standalone to wrap regular functions:

import { debounce, throttle } from '@nano_kit/store'
const performSearch = debounce(300)((query: string) => {
console.log('Searching for:', query)
})
const handleScroll = throttle(100)(() => {
console.log('Scroll position:', window.scrollY)
})

interval creates a signal with a tick counter. The timer starts when the signal becomes active and is cleared when it becomes inactive.

import { interval, effect } from '@nano_kit/store'
const $tick = interval(1000)
const stop = effect(() => {
console.log('Tick:', $tick())
})
/* Later: clears the underlying interval */
stop()

previous creates a computed that tracks the previous value of a signal. Returns undefined for the first read.

import { signal, previous, effect } from '@nano_kit/store'
const $count = signal(1)
const $prevCount = previous($count)
effect(() => {
console.log(`Changed from ${$prevCount()} to ${$count()}`)
})
$count(2) /* Changed from 1 to 2 */
$count(3) /* Changed from 2 to 3 */

latest merges several sources into one computed that carries the value of the source that changed last. It fits a local cell paired with a read-only source: typing wins over the URL, and navigation wins over what was typed. Where previous looks back through a single source, latest picks the freshest value across several.

import { signal, latest, effect } from '@nano_kit/store'
/* Stands for a read-only source, such as a search param of the URL */
const $searchParam = signal('shoes')
/* The local cell the search field writes */
const $searchQuery = signal('')
const $search = latest($searchQuery, $searchParam)
effect(() => {
console.log('Search:', $search())
})
/* Search: shoes */
$searchQuery('boots') /* Search: boots */
$searchParam('hats') /* Search: hats */

On the first read the last source wins, and when several sources changed since the previous read, as with writes inside one batch, the last of them in argument order wins. Only a new value counts as a change: writing a value equal to the current one leaves the result as it is.

length creates a computed for the length property of arrays or strings.

import { signal, length, effect } from '@nano_kit/store'
const $items = signal(['a', 'b', 'c'])
const $itemCount = length($items)
console.log('Count:', $itemCount()) /* Count: 3 */

boolean converts a signal’s value to a boolean.

import { signal, boolean } from '@nano_kit/store'
const $user = signal(null)
const $hasUser = boolean($user)
console.log($hasUser()) /* false */
$user({ name: 'Dan' })
console.log($hasUser()) /* true */

isFunction checks if a value is a function.

import { isFunction } from '@nano_kit/store'
isFunction(() => {}) /* true */
isFunction(42) /* false */

isAccessor checks if a value is an accessor (function).

import { isAccessor } from '@nano_kit/store'
const $value = () => 42
isAccessor($value) /* true */
isAccessor(42) /* false */

isSignal checks if a value is a signal.

import { signal, computed, isSignal } from '@nano_kit/store'
const $count = signal(0)
const $doubled = computed(() => $count() * 2)
const $accessor = () => 42
isSignal($count) /* true */
isSignal($doubled) /* true */
isSignal($accessor) /* false */

isEmpty checks if a value is null or undefined.

import { isEmpty } from '@nano_kit/store'
isEmpty(null) /* true */
isEmpty(undefined) /* true */
isEmpty(0) /* false */
isEmpty('') /* false */

$get extracts a value from either a plain value or an accessor. Tracks dependencies when called inside an effect.

import { signal, $get } from '@nano_kit/store'
const $count = signal(5)
$get($count) /* 5 */
$get(10) /* 10 */
$get(() => 15) /* 15 */

get — same as $get but always reads without tracking dependencies (untracked). Useful when you need the current value inside an effect without subscribing to future changes.

import { signal, effect, get } from '@nano_kit/store'
const $a = signal(1)
const $b = signal(10)
effect(() => {
/* Tracks $a, re-runs when $a changes */
console.log('A:', $a())
/* Reads $b without tracking */
console.log('B:', get($b))
})

toSignal converts a value, accessor, or signal into a writable signal.

import { signal, computed, toSignal } from '@nano_kit/store'
const $a = toSignal(42) /* Creates signal(42) */
const $b = toSignal(signal(10)) /* Returns input signal */
const $c = toSignal(computed(() => 5)) /* Returns input computed */
const $d = toSignal(() => 20) /* Creates computed(() => 20) */

toAccessor converts a value into an accessor, or returns the accessor if already a function.

import { signal, computed, toAccessor } from '@nano_kit/store'
const $a = toAccessor(42) /* Creates () => 42 */
const $b = toAccessor(signal(10)) /* Returns input signal */
const $c = toAccessor(computed(() => 5)) /* Returns input computed */
const $d = toAccessor(() => 20) /* Returns input accessor */

toAccessorOrSignal converts a value into a signal, or returns the accessor/signal if already a function.

import { signal, computed, toAccessorOrSignal } from '@nano_kit/store'
const $a = toAccessorOrSignal(42) /* Creates signal(42) */
const $b = toAccessorOrSignal(signal(10)) /* Returns input signal */
const $c = toAccessorOrSignal(computed(() => 5)) /* Returns input computed */
const $d = toAccessorOrSignal(() => 20) /* Returns input accessor */

composeDestroys combines multiple cleanup functions into a single function.

import { effect, composeDestroys } from '@nano_kit/store'
const cleanup1 = () => console.log('Cleanup 1')
const cleanup2 = () => console.log('Cleanup 2')
const stop = effect(() => {
/* ... */
return composeDestroys(cleanup1, cleanup2)
})
stop() /* Logs: Cleanup 1, Cleanup 2 */

noop is a shared empty function, and identity returns the value it receives. Use them when you need a reusable no-op or identity callback instead of creating new local functions.

import { noop, identity } from '@nano_kit/store'
const cleanup = enabled
? subscribe($value, onValue)
: noop
const codec = {
encode: identity,
decode: identity
}