An open API service indexing awesome lists of open source software.

https://github.com/nanostores/nanostores

A tiny (340 bytes) state manager for React/RN/Preact/Vue/Svelte with many atomic tree-shakable stores
https://github.com/nanostores/nanostores

Last synced: about 1 month ago
JSON representation

A tiny (340 bytes) state manager for React/RN/Preact/Vue/Svelte with many atomic tree-shakable stores

Awesome Lists containing this project

README

          

# Nano Stores

A tiny state manager for **React**, **React Native**, **Preact**, **Vue**,
**Svelte**, **Solid**, **Lit**, **Angular**, andĀ vanilla JS.
ItĀ usesĀ **manyĀ atomicĀ stores** andĀ direct manipulation.

- **Small.** Between 351 and 844 bytes (minified and brotlied).
Zero dependencies. ItĀ usesĀ [SizeĀ Limit]Ā toĀ control size.
- **Fast.** With small atomic and derived stores, you do not need to call
the selector function forĀ allĀ componentsĀ onĀ every store change.
- **Tree Shakable.** A chunk contains only stores used by components
in the chunk.
- Designed to move logic from components to stores.
- Good **TypeScript** support.

```ts
// store/users.ts
import { atom } from 'nanostores'

export const $users = atom([])

export function addUser(user: User) {
$users.set([...$users.get(), user])
}
```

```ts
// store/admins.ts
import { computed } from 'nanostores'

import { $users } from './users.ts'

export const $admins = computed($users, users => users.filter(i => i.isAdmin))
```

```tsx
// components/admins.tsx
import { useStore } from '@nanostores/react'

import { $admins } from '../stores/admins.ts'

export const Admins = () => {
const admins = useStore($admins)
return (


    {admins.map(user => (

    ))}

)
}
```

---

Ā Ā Nano Stores is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.

---

[SizeĀ Limit]: https://github.com/ai/size-limit

## Table of Contents

- [Table of Contents](#table-of-contents)
- [Install](#install)
- [Smart Stores](#smart-stores)
- [Devtools](#devtools)
- [Guide](#guide)
- [Atoms](#atoms)
- [Maps](#maps)
- [Lazy Stores](#lazy-stores)
- [Computed Stores](#computed-stores)
- [Value Comparison](#value-comparison)
- [Effects](#effects)
- [Batching](#batching)
- [Map Creator](#map-creator)
- [Tasks](#tasks)
- [Store Events](#store-events)
- [Integration](#integration)
- [React \& Preact](#react--preact)
- [Vue](#vue)
- [Svelte](#svelte)
- [Solid](#solid)
- [Lit](#lit)
- [Web Components](#web-components)
- [Angular](#angular)
- [Alpine.js](#alpinejs)
- [Vanilla JS](#vanilla-js)
- [Server-Side Rendering](#server-side-rendering)
- [Tests](#tests)
- [Best Practices](#best-practices)
- [Move Logic from Components to Stores](#move-logic-from-components-to-stores)
- [Separate changes and reaction](#separate-changes-and-reaction)
- [Reduce `get()` usage outside of tests](#reduce-get-usage-outside-of-tests)
- [Known Issues](#known-issues)
- [ESM](#esm)

## Install

```sh
npm install nanostores
```

## Smart Stores

- [Async computed](https://github.com/nanostores/async) store
to fetch data or create chains of async operations.
- [Persistent](https://github.com/nanostores/persistent) store to save data
to `localStorage` and synchronize changes between browser tabs.
- [Storage](https://github.com/vp-tw/nanostores-storage) stores for advanced
storage use cases with `localStorage`, `sessionStorage`, memory, and custom
adapters.
- [Router](https://github.com/nanostores/router) store to parse URL
and implements SPA navigation.
- [Media Query](https://github.com/nanostores/media-query) store sync value
with media query.
- [Deep Map](https://github.com/nanostores/deepmap) store to put
big nested object/arrays and change keys by path.
- [I18n](https://github.com/nanostores/i18n) library based on stores
to make application translatable.
- [Query](https://github.com/nanostores/query) store that helps you with smart
remote data fetching.
- [SQL](https://github.com/nanostores/sql) reactive store for `SELECT` from
SQLite for browser or React Native.
- [dataLayer](https://github.com/vp-tw/nanostores-data-layer) store to sync
Google Tag Manager `dataLayer` pushes with Nano Stores.
- [Logux Client](https://github.com/logux/client): stores with WebSocket
sync and CRDT conflict resolution.
- [Immer](https://github.com/illuxiza/nanostores-immer) plugin to
enable immutable state updates using Immer.
- [qs](https://github.com/VdustR/nanostores-qs) manages the query string
in the URL.
- [Form](https://github.com/alexcarpenter/form) for headless forms.
- [Machine](https://github.com/alexcarpenter/machine) for state machines.

## Devtools

- [Redux DevTools](https://nanostores-devtools.psdcoder.dev/) integration that detects stores and shows their state and changes in the Redux DevTools browser extension.
- [Logger](https://github.com/nanostores/logger) of lifecycle, changes
in the browser console.
- [Vue Devtools](https://github.com/nanostores/vue#devtools) plugin that detects
stores and attaches them to devtools inspectors and timeline.

## Guide

### 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.

```ts
import { atom } from 'nanostores'

export const $counter = atom(0)
```

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

```ts
export type LoadingStateValue = 'empty' | 'loading' | 'loaded'

export const $loadingState = atom('empty')
```

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

```ts
import type { StoreValue } from 'nanostores'

type Value = StoreValue //=> LoadingStateValue
```

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

```ts
$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](#react--preact)/[Vue](#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.

```ts
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()`](#effects) if you want to subscribe to multiple stores.

[router]: https://github.com/nanostores/router

### Maps

Map store can be used to store objects with one level of depth and change keys
in this object.

To create map store call `map(initial)` function with initial object.

```ts
import { map } from 'nanostores'

export const $profile = map({
name: 'anonymous'
})
```

In TypeScript, you can pass type parameter with store’s type:

```ts
export interface ProfileValue {
name: string
email?: string
}

export const $profile = map({
name: 'anonymous'
})
```

`store.set(object)` or `store.setKey(key, value)` methods will change the store.

```ts
$profile.setKey('name', 'Kazimir Malevich')
```

Setting `undefined` will remove optional key:

```ts
$profile.setKey('email', undefined)
```

Store’s listeners will receive third argument with changed key.

```ts
$profile.listen((profile, oldProfile, changed) => {
if (changed) console.log(`${changed} new value ${profile[changed]}`)
})
```

You can also listen for specific keys of the store being changed, using
`listenKeys` and `subscribeKeys`.

```ts
listenKeys($profile, ['name'], (value, oldValue, changed) => {
console.log(`$profile.Name new value ${value.name}`)
})
```

Nested mutations can be listened to using a base key. For example, listening to `user` will trigger on `user.name` mutations:

```ts
// Mutating user.name triggers the listener
listenKeys($state, ['user'], (value, oldValue, changed) => {
console.log(`user changed: ${changed}`)
})
```

`subscribeKeys(store, keys, cb)` in contrast with `listenKeys(store, keys, cb)`
also call listeners immediately during the subscription.
Please note that when using subscribe for store changes, the initial evaluation
of the callback has undefined old value and changed key.

### Lazy Stores

A unique feature of Nano Stores is that every state has two modes:

- **Mount:** when one or more listeners is mounted to the store.
- **Disabled:** when store has no listeners.

Nano Stores was created to move logic from components to the store.
Stores can listen for URL changes or establish network connections.
Mount/disabled modes allow you to create lazy stores, which will use resources
only if store is really used in the UI.

`onMount` sets callback for mount and disabled states.

```ts
import { onMount } from 'nanostores'

onMount($profile, () => {
// Mount mode
return () => {
// Disabled mode
}
})
```

For performance reasons, store will move to disabled mode with 1-second delay
after last listener unsubscribing.

Call `keepMount()` to test store’s lazy initializer in tests and `cleanStores`
to unmount them after test.

```js
import { cleanStores, keepMount } from 'nanostores'

import { $profile } from './profile.js'

afterEach(() => {
cleanStores($profile)
})

it('is anonymous from the beginning', () => {
keepMount($profile)
// Checks
})
```

### Computed Stores

Computed store is based on other store’s value.

```ts
import { computed } from 'nanostores'

import { $users } from './users.js'

export const $admins = computed($users, users => {
// This callback will be called on every `users` changes
return users.filter(user => user.isAdmin)
})
```

Use [`@nanostores/async`] for async computed:

```js
import { computedAsync } from '@nanostores/async'

const $org = computedAsync($orgSlug, slug => {
return fetchJson(`/organizations/${slug}`)
})

// The callback receives the resolved org, not an AsyncValue wrapper.
const $profile = computedAsync([$org, $userId], (org, userId) => {
return fetchJson(`/users/${org.id}/${userId}`)
})
```

By default, `computed` stores update _each_ time any of their dependencies
gets updated. If you are fine with waiting until the end of a tick, you can
use `batched`. The only difference with `computed` is that it will wait until
the end of a tick to update itself.

```ts
import { batched } from 'nanostores'

const $sortBy = atom('id')
const $categoryId = atom('')

export const $link = batched([$sortBy, $categoryId], (sortBy, categoryId) => {
return `/api/entities?sortBy=${sortBy}&categoryId=${categoryId}`
})

// `batched` will update only once even you changed two stores
export function resetFilters() {
$sortBy.set('date')
$categoryIdFilter.set('1')
}
```

Both `computed` and `batched` can be calculated from multiple stores:

```ts
import { $lastVisit } from './lastVisit.js'
import { $posts } from './posts.js'

export const $newPosts = computed([$lastVisit, $posts], (lastVisit, posts) => {
return posts.filter(post => post.publishedAt > lastVisit)
})
```

### Value Comparison

Every store compares the old and the new value on `set()` with `Object.is()`.
When the values are the same, the store keeps the old value and no listener
is called.

You can set `store.eq` to have custom comparison and avoid unnecessary
listeners calls. It is useful for stores with objects or arrays inside,
especially for computed stores, which create a new object on every run.

```ts
import equal from 'fast-deep-equal/es6'

// Now `$visibleIds` keeps its old array when the new one has the same items
export const $visibleIds = computed($posts, posts => posts.map(post => post.id))
$visibleIds.eq = equal
```

Three things to keep in mind:

- The old value can be `undefined` on the first call, for instance on the first
run of a computed store.
- The function belongs to the store, so all its users share it.
- `store.notify()` still calls listeners, even when values are equal.

`map()` stores have a 2 functions, `store.eq` for `store.set()` and `store.eqKey` for `setKey()` calls. `eqKey` receives old value, new value, and key’s name
to have a different logic for specific key.

```ts
const $settings = map({ theme: 'dark', tags: [] })
$settings.eqKey = equal
```

### Effects

`effect` subscribes for multiple atoms at once.

`effect` runs its callback on the start, with initial values, as well as
on any stores change. If callback returns cleanup function it will be performed
before next callback run. Besides that, `effect` returns own cleanup function,
which allows cancelling the whole effect.

```js
const $enabled = atom(true)
const $interval = atom(1000)

const cancelPing = effect([$enabled, $interval], (enabled, interval) => {
if (!enabled) return

const intervalId = setInterval(() => {
sendPing()
}, interval)

return () => {
clearInterval(intervalId)
}
})
```

### Batching

`batch` groups multiple store writes into a single transaction. Listeners and
effects fire at most once when the outermost `batch` returns, observing the
final values. Batches can be nested; only the outermost flush triggers the
notifications.

```js
import { atom, batch } from 'nanostores'

const $firstName = atom('')
const $lastName = atom('')

batch(() => {
$firstName.set('Ada')
$lastName.set('Lovelace')
})
// effects depending on either atom run once, with both new values visible
```

Inside a `batch`, `Map#setKey` writes are coalesced too. The listener fires
once and its `changed` argument is `undefined` (the batch touched multiple
keys). `listenKeys` subscribers fire once if any key they watch ends the batch
with a different value, and not at all if only other keys changed. Outside
a `batch`, each `setKey` still notifies with its own `changed` key as before.

### Map Creator

If you have many similar stores (for instance, in advanced database ORM),
you can define map creator (like a ā€œclassā€ in OOP).

```js
const User = mapCreator((store, id) => {
store.set({ id, isLoading: true })
fetchUser(id).then(data => {
store.set({ id, isLoading: false, data })
})
})

let user1 = User('1')
```

### Tasks

`startTask()` and `task()` can be used to mark all async operations
during store initialization.

```ts
import { task } from 'nanostores'

onMount($post, () => {
task(async () => {
$post.set(await loadPost())
})
})
```

You can wait for all ongoing tasks end in tests or SSR with `await allTasks()`.

```jsx
import { allTasks } from 'nanostores'

$post.listen(() => {}) // Move store to active mode to start data loading
await allTasks()

const html = ReactDOMServer.renderToString()
```

### Store Events

Each store has a few events, which you listen:

- `onMount(store, cb)`: first listener was subscribed with debounce.
We recommend to always use `onMount` instead of `onStart + onStop`,
because it has a short delay to prevent flickering behavior.
- `onStart(store, cb)`: first listener was subscribed. Low-level method.
It is better to use `onMount` for simple lazy stores.
- `onStop(store, cb)`: last listener was unsubscribed. Low-level method.
It is better to use `onMount` for simple lazy stores.
- `onSet(store, cb)`: before applying any changes to the store.
- `onNotify(store, cb)`: before notifying store’s listeners about changes.

`onSet` and `onNotify` events has `abort()` function to prevent changes
or notification.

```ts
import { onSet } from 'nanostores'

onSet($store, ({ newValue, abort }) => {
if (!validate(newValue)) {
abort()
}
})
```

Event listeners can communicate with `payload.shared` object.

## Integration

### React & Preact

Use [`@nanostores/react`] or [`@nanostores/preact`] package
and `useStore()` hook to get store’s value and re-render component
on store’s changes.

```tsx
import { useStore } from '@nanostores/react' // or '@nanostores/preact'

import { $profile } from '../stores/profile.js'

export const Header = ({ postId }) => {
const profile = useStore($profile)
return Hi, {profile.name}
}
```

In React `useLoadingStore()` suspends the component while the store is loading.
It supports both loading formats: the state machine of [`@nanostores/async`]
and the `isLoading` key of [Logux Client] and [`@nanostores/sql`].

```ts
// stores/user.ts
import { computedAsync } from '@nanostores/async'
import { atom } from 'nanostores'

export const $userId = atom('user-1')

export const $user = computedAsync($userId, userId => {
return fetch(`/api/users/${userId}`).then(response => response.json())
})
```

[`@nanostores/async`]: https://github.com/nanostores/async
[`@nanostores/sql`]: https://github.com/nanostores/sql
[Logux Client]: https://github.com/logux/client
[`@nanostores/preact`]: https://github.com/nanostores/preact
[`@nanostores/react`]: https://github.com/nanostores/react

### Vue

Use [`@nanostores/vue`] and `useStore()` composable function
to get store’s value and re-render component on store’s changes.

```vue

import { useStore } from '@nanostores/vue'
import { $profile } from '../stores/profile.js'

const props = defineProps(['postId'])

const profile = useStore($profile)

Hi, {{ profile.name }}

```

[`@nanostores/vue`]: https://github.com/nanostores/vue

### Svelte

Nano Stores works with `.svelte` files out of the box because they implement [Svelte's store contract]:

```svelte

import { profile } from '../stores/profile.js'

Hi, {$profile.name}
```

But for `.svelte.ts` files or if you prefer new runes API, you can use `useStore()` reactive wrapper from [`@nanostores/svelte-runes`] (use `store.current` to read value):

```svelte

import { useStore } from '@nanostores/svelte-runes'
import { profile } from '../stores/profile.js'

let user = useStore(profile)

Hi, {user.current.name}
```

In other frameworks, Nano Stores promote code style to use `$` prefixes
for store’s names. But in Svelte it has a special meaning, so we recommend
to not follow this code style here.

[`@nanostores/svelte-runes`]: https://github.com/nanostores/svelte-runes
[Svelte's store contract]: https://svelte.dev/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values

### Solid

Use [`@nanostores/solid`] and `useStore()` composable function
to get store’s value and re-render component on store’s changes.

```js
import { useStore } from '@nanostores/solid'

import { $profile } from '../stores/profile.js'

export function Header({ postId }) {
const profile = useStore($profile)
return Hi, {profile().name}
}
```

[`@nanostores/solid`]: https://github.com/nanostores/solid

### Lit

Use [`@nanostores/lit`] and `StoreController` reactive controller
to get store’s value and re-render component on store’s changes.

```ts
import { StoreController } from '@nanostores/lit'

import { $profile } from '../stores/profile.js'

@customElement('my-header')
class MyElement extends LitElement {
@property()
private profileController = new StoreController(this, $profile)

render() {
return html`Hi, ${profileController.value.name}`
}
}
```

[`@nanostores/lit`]: https://github.com/nanostores/lit

### Angular

Use [`@nanostores/angular`] and `NanostoresService` with `useStore()`
method to get store’s value and subscribe for store’s changes.

```ts
// NgModule:
import { NANOSTORES, NanostoresService } from '@nanostores/angular';

@NgModule({
providers: [{ provide: NANOSTORES, useClass: NanostoresService }]
})
```

```tsx
// Component:
import { Component } from '@angular/core'
import { NanostoresService } from '@nanostores/angular'
import { Observable, switchMap } from 'rxjs'

import { profile } from '../stores/profile'
import { IUser, User } from '../stores/user'

@Component({
selector: 'app-root',
template: '

{{ user.name }}

'
})
export class AppComponent {
currentUser$: Observable = this.nanostores
.useStore(profile)
.pipe(switchMap(userId => this.nanostores.useStore(User(userId))))

constructor(private nanostores: NanostoresService) {}
}
```

[`@nanostores/angular`]: https://github.com/nanostores/angular

### Alpine.js

Use [`@nanostores/alpine`] plugin and `x-nano` directive to bind stores
to Alpine.js components.

```js
import { NanoStores } from '@nanostores/alpine'
import Alpine from 'alpinejs'

import { $profile } from '../stores/profile.js'

Alpine.plugin(NanoStores)
Alpine.magic('profile', () => $profile)
Alpine.start()
```

```html




```

[`@nanostores/alpine`]: https://github.com/nanostores/alpine

### Web Components

[nanotags](https://psd-coder.github.io/nanotags) is a thin Web Components wrapper powered by Nano Stores reactivity. It leans on the platform—Custom Elements, standard DOM, regular CSS—instead of reinventing them. The result is a typed, reactive component model with automatic cleanup in under 2.5 KB.

```html

0
+1

```

```typescript
import { define } from 'nanotags'

const Counter = define('x-counter')
.withProps(p => ({
count: p.number()
}))
.withRefs(r => ({
increment: r.one('button'),
display: r.one('span')
}))
.setup(ctx => {
ctx.on(ctx.refs.increment, 'click', () => {
ctx.props.$count.set(ctx.props.$count.get() + 1)
})

ctx.effect(ctx.props.$count, value => {
ctx.refs.display.textContent = String(value)
})
})
```

### Vanilla JS

`Store#subscribe()` calls callback immediately and subscribes to store changes.
It passes store’s value to callback.

```js
import { $profile } from '../stores/profile.js'

$profile.subscribe(profile => {
console.log(`Hi, ${profile.name}`)
})
```

`Store#listen(cb)` in contrast, calls only on next store change. It could be
useful for a multiple stores listeners.

```js
function render() {
console.log(`${$post.get().title} for ${$profile.get().name}`)
}

$profile.listen(render)
$post.listen(render)
render()
```

See also `listenKeys(store, keys, cb)` to listen for specific keys changes
in the map.

### Server-Side Rendering

Nano Stores support SSR. Use standard strategies.

```js
if (isServer) {
$settings.set(initialSettings)
$router.open(renderingPageURL)
}
```

You can wait for async operations (for instance, data loading
via isomorphic `fetch()`) before rendering theĀ page:

```jsx
import { allTasks } from 'nanostores'

$post.listen(() => {}) // Move store to active mode to start data loading
await allTasks()

const html = ReactDOMServer.renderToString()
```

### Tests

Adding an empty listener by `keepMount(store)` keeps the store
in active mode during the test. `cleanStores(store1, store2, …)` cleans
stores used in the test.

```ts
import { cleanStores, keepMount } from 'nanostores'

import { $profile } from './profile.js'

afterEach(() => {
cleanStores($profile)
})

it('is anonymous from the beginning', () => {
keepMount($profile)
expect($profile.get()).toEqual({ name: 'anonymous' })
})
```

You can use `allTasks()` to wait all async operations in stores.

```ts
import { allTasks } from 'nanostores'

it('saves user', async () => {
saveUser()
await allTasks()
expect(analyticsEvents.get()).toEqual(['user:save'])
})
```

## Best Practices

### Move Logic from Components to Stores

Stores are not only to keep values. You can use them to track time, to load data
from server.

```ts
import { atom, onMount } from 'nanostores'

export const $currentTime = atom(Date.now())

onMount($currentTime, () => {
$currentTime.set(Date.now())
const updating = setInterval(() => {
$currentTime.set(Date.now())
}, 1000)
return () => {
clearInterval(updating)
}
})
```

Use derived stores to create chains of reactive computations.

```ts
import { computed } from 'nanostores'

import { $currentTime } from './currentTime.js'

const appStarted = Date.now()

export const $userInApp = computed($currentTime, currentTime => {
return currentTime - appStarted
})
```

We recommend moving all logic, which is not highly related to UI, to the stores.
Let your stores track URL routing, validation, sending data to a server.

With application logic in the stores, it is much easier to write and run tests.
It is also easy to change your UI framework. For instance, add React Native
version of the application.

### Separate changes and reaction

Use a separated listener to react on new store’s value, not an action function
where you change this store.

```diff
function increase() {
$counter.set($counter.get() + 1)
- printCounter(store.get())
}

+ $counter.listen(counter => {
+ printCounter(counter)
+ })
```

An action function is not the only way for store to a get new value.
For instance, persistent store could get the new value from another browser tab.

With this separation your UI will be ready to any source of store’s changes.

### Reduce `get()` usage outside of tests

`get()` returns current value, and it is a good solution for tests.

But it is better to use `useStore()`, `$store`, or `Store#subscribe()` in UI
to subscribe to store changes and always render the actual data.

```diff
- const { userId } = $profile.get()
+ const { userId } = useStore($profile)
```