Skip to content
On this page

Atoms

Atom store can be used to store strings, numbers, arrays.

You can use it for objects too if you want to prohibit key changes and allow only replacing the whole object (like we do in router).

To create it call atom(initial) and pass initial value as a first argument.

import { atom } from 'nanostores'
export const $counter = atom(0)

In TypeScript, you can optionally pass value type as type parameter.

export type LoadingStateValue = 'empty' | 'loading' | 'loaded'
export const $loadingState = atom<LoadingStateValue>('empty')

Then you can use StoreValue<Store> helper to get store’s value type in TypeScript:

import type { StoreValue } from 'nanostores'
type Value = StoreValue<typeof $loadingState> //=> LoadingStateValue

store.get() will return store’s current value. store.set(nextValue) will change value.

$counter.set($counter.get() + 1)

store.subscribe(cb) and store.listen(cb) can be used to subscribe for the changes in vanilla JS. For React/Vue we have extra special helpers useStore to re-render the component on any store changes.

Listener callbacks will receive the updated value as a first argument and the previous value as a second argument.

const unbindListener = $counter.subscribe((value, oldValue) => {
console.log(`counter value changed from ${oldValue} to ${value}`)
})

store.subscribe(cb) in contrast with store.listen(cb) also call listeners immediately during the subscription. Note that the initial call for store.subscribe(cb) will not have any previous value and oldValue will be undefined.

See also effect() if you want to subscribe to multiple stores.


Imported from the Nano Stores README for version 1.5.5. Improve this page there.