Nano stores

A tiny (258 bytes) state manager for React/RN/Preact/Vue/Svelte with many a...

README

Nano Stores


<img align="right" width="92" height="92" title="Nano Stores logo"
     src="https://nanostores.github.io/nanostores/logo.svg">

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

Small. Between 266 and 969 bytes (minified and gzipped).
  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. The chunk contains only stores used by components
  in the chunk.
Was designed to move logic from components to stores.
It has good TypeScript support.

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

  4. export const users = atom<User[]>([])

  5. export function addUser(user: User) {
  6.   users.set([...users.get(), user]);
  7. }
  8. ```

  1. ```ts
  2. // store/admins.ts
  3. import { computed } from 'nanostores'
  4. import { users } from './users.js'

  5. export const admins = computed(users, list =>
  6.   list.filter(user => user.isAdmin)
  7. )
  8. ```

  1. ```tsx
  2. // components/admins.tsx
  3. import { useStore } from '@nanostores/react'
  4. import { admins } from '../stores/admins.js'

  5. export const Admins = () => {
  6.   const list = useStore(admins)
  7.   return (
  8.     <ul>
  9.       {list.map(user => <UserItem user={user} />)}
  10.     </ul>
  11.   )
  12. }
  13. ```

  <img src="https://evilmartians.com/badges/sponsored-by-evil-martians.svg"
       alt="Sponsored by Evil Martians" width="236" height="54">

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

Table of Contents


Integration
  Vue
  Svelte
  Solid
  Tests

Install


  1. ```sh
  2. npm install nanostores
  3. ```

Tools


Persistent store to save data
  to localStorage and synchronize changes between browser tabs.
Router store to parse URL
  and implements SPA navigation.
I18n library based on stores
  to make application translatable.
Logux Client: stores with WebSocket
  sync and CRDT conflict resolution.

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.

  1. ```ts
  2. import { atom } from 'nanostores'

  3. export const counter = atom(0)
  4. ```

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

  1. ```ts
  2. export type LoadingStateValue = 'empty' | 'loading' | 'loaded'
  3. export const loadingState = atom<LoadingStateValue>('empty')
  4. ```

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

  1. ```ts
  2. counter.set(counter.get() + 1)
  3. ```

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
to re-render the component on any store changes.

  1. ```ts
  2. const unbindListener = counter.subscribe(value => {
  3.   console.log('counter value:', value)
  4. })
  5. ```

store.subscribe(cb) in contrast with store.listen(cb) also call listeners
immediately during the subscription.

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

Maps


Map store can be used to store objects and change keys in this object.

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

  1. ```ts
  2. import { map } from 'nanostores'

  3. export const profile = map({
  4.   name: 'anonymous'
  5. })
  6. ```

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

  1. ```ts
  2. export interface ProfileValue {
  3.   name: string,
  4.   email?: string
  5. }

  6. export const profile = map<ProfileValue>({
  7.   name: 'anonymous'
  8. })
  9. ```

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

  1. ```ts
  2. profile.setKey('name', 'Kazimir Malevich')
  3. ```

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

  1. ```ts
  2. profile.listen((value, changed) => {
  3.   console.log(`${changed} new value ${value[changed]}`)
  4. })
  5. ```

You can use store.notify() to trigger listeners without changing value
in the key for performance reasons.

  1. ```ts
  2. store.get().bigList.push(newItem)
  3. store.notify('bigList')
  4. ```

Maps Templates


Map templates was created for similar stores like for the store
for each post in the blog where you have many posts. It is like class in ORM frameworks.

This is advanced tool, which could be too complicated to be used
on every case. But it will be very useful for creating libraries
like react-query. See [Logux Client] for example.

Nano Stores has map templates, to use a separated store
for each item because of:

1. Performance: components can subscribe to the changes on specific post.
2. Lists can’t reflect that only specific subset of posts was loaded
   from the server.

mapTemplate(init) creates template. init callback will receive item’s
store and ID.

  1. ```ts
  2. import { mapTemplate } from 'nanostores'

  3. export interface PostValue {
  4.   id: string
  5.   title: string
  6.   updatedAt: number
  7. }

  8. export const Post = mapTemplate<PostValue>((newPost, id) => {
  9.   newPost.setKey('title', 'New post')
  10.   newPost.setKey('updatedAt', Date.now())
  11. })
  12. ```

Each item of the template must have value.id.

  1. ```ts
  2. let post1 = Post('1')
  3. post1.get().id //=> '1'
  4. ```

[Logux Client]: https://github.com/logux/client

Lazy Stores


Nano Stores unique feature is that every state have 2 modes:

Mount: when one or more listeners was mount to the store.
Disabled: when store has no listeners.

Nano Stores was created to move logic from components to the store.
Stores can listen 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.

  1. ```ts
  2. import { onMount } from 'nanostores'

  3. onMount(profile, () => {
  4.   // Mount mode
  5.   return () => {
  6.     // Disabled mode
  7.   }
  8. })
  9. ```

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

Map templates can use init callback for code for mount and disabled modes:

  1. ```ts
  2. mapTemplate((post, id) => {
  3.   // Mount mode
  4.   let unsubscribe = loadDataAndSubscribe(`/posts/${id}`, data => {
  5.     post.set(data)
  6.   })
  7.   return () => {
  8.     // Disabled mode
  9.     unsubscribe()
  10.   }
  11. })
  12. ```

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

  1. ``` js
  2. import { cleanStores, keepMount } from 'nanostores'
  3. import { Post } from './profile.js'

  4. afterEach(() => {
  5.   cleanStores(Post)
  6. })

  7. it('is anonymous from the beginning', () => {
  8.   let post = Post(1)
  9.   keepMount(post)
  10.   // Checks
  11. })
  12. ```

Map template will keep cache of all mount stores:

  1. ```ts
  2. postA = Post('same ID')
  3. postB = Post('same ID')
  4. postA === postB //=> true
  5. ```

Computed Stores


Computed store is based on other store’s value.

  1. ```ts
  2. import { computed } from 'nanostores'
  3. import { users } from './users.js'

  4. export const admins = computed(users, all => {
  5.   // This callback will be called on every `users` changes
  6.   return all.filter(user => user.isAdmin)
  7. })
  8. ```

You can combine a value from multiple stores:

  1. ```ts
  2. import { lastVisit } from './lastVisit.js'
  3. import { posts } from './posts.js'

  4. export const newPosts = computed([lastVisit, posts], (when, allPosts) => {
  5.   return allPosts.filter(post => post.publishedAt > when)
  6. })
  7. ```

Actions


Action is a function that changes a store. It is a good place to move
business logic like validation or network operations.

Wrapping functions with action() can track who changed the store
in the logger.

  1. ```ts
  2. import { action } from 'nanostores'

  3. export const increase = action(counter, 'increase', (store, add) => {
  4.   if (validateMax(store.get() + add)) {
  5.     store.set(store.get() + add)
  6.   }
  7.   return store.get()
  8. })

  9. increase(1) //=> 1
  10. increase(5) //=> 6
  11. ```

Actions for map template can be created with actionFor():

  1. ```ts
  2. import { actionFor } from 'nanostores'

  3. export const rename = actionFor(Post, 'rename', async (store, newTitle) => {
  4.   await api.updatePost({
  5.     id: store.get().id,
  6.     title: newTitle
  7.   })
  8.   store.setKey('title', newTitle)
  9.   store.setKey('updatedAt', Date.now())
  10. })

  11. await rename(post, 'New title')
  12. ```

All running async actions are tracked by allTasks(). It can simplify
tests with chains of actions.

  1. ```ts
  2. import { allTasks } from 'nanostores'

  3. renameAllPosts()
  4. await allTasks()
  5. ```

Tasks


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

  1. ```ts
  2. import { task } from 'nanostores'

  3. onMount(post, () => {
  4.   task(async () => {
  5.     post.set(await loadPost())
  6.   })
  7. })
  8. ```

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

  1. ``` js
  2. import { allTasks } from 'nanostores'

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

  5. const html = ReactDOMServer.renderToString(<App />)
  6. ```

Async actions will be wrapped to task() automatically.

  1. ```ts
  2. rename(post1, 'New title')
  3. rename(post2, 'New title')
  4. await allTasks()
  5. ```

Store Events


Each store has a few events, which you listen:

onStart(store, cb): first listener was subscribed.
onStop(store, cb): last listener was unsubscribed.
onMount(store, cb): shortcut to use both onStart and onStop.
  We recommend to always use onMount instead of onStart + onStop,
  because it has a short delay to prevent flickering behavior.
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.

  1. ```ts
  2. import { onSet } from 'nanostores'

  3. onSet(store, ({ newValue, abort }) => {
  4.   if (!validate(newValue)) {
  5.     abort()
  6.   }
  7. })
  8. ```

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

  1. ```tsx
  2. import { useStore } from '@nanostores/react' // or '@nanostores/preact'
  3. import { profile } from '../stores/profile.js'
  4. import { Post } from '../stores/post.js'

  5. export const Header = ({ postId }) => {
  6.   const user = useStore(profile)
  7.   const post = useStore(Post(postId))
  8.   return <header>{post.title} for {user.name}</header>
  9. }
  10. ```

[@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.

  1. ```vue
  2. <template>
  3.   <header>{{ post.title }} for {{ user.name }}</header>
  4. </template>
  5. <script>
  6.   import { useStore } from '@nanostores/vue'

  7.   import { profile } from '../stores/profile.js'
  8.   import { Post } from '../stores/post.js'

  9.   export default {
  10.     setup (props) {
  11.       const user = useStore(profile)
  12.       const post = useStore(Post(props.postId))
  13.       return { user, post }
  14.     }
  15.   }
  16. </script>
  17. ```

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

Svelte


Every store implements
Put $ before store variable to get store’s
value and subscribe for store’s changes.

  1. ```svelte
  2. <script>
  3.   import { profile } from '../stores/profile.js'
  4.   import { Post } from '../stores/post.js'

  5.   export let postId

  6.   const post = Post(postId)
  7. </script>
  8. <header>{$post.title} for {$profile.name}</header>
  9. ```

Solid


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

  1. ``` js
  2. import { useStore } from '@nanostores/solid'
  3. import { profile } from '../stores/profile.js'
  4. import { Post } from '../stores/post.js'

  5. export function Header({ postId }) {
  6.   const user = useStore(profile)
  7.   const post = useStore(Post(postId))
  8.   return <header>{post().title} for {user().name}</header>
  9. }
  10. ```

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

Vanilla JS


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

  1. ``` js
  2. import { profile } from '../stores/profile.js'
  3. import { Post } from '../stores/post.js'

  4. const post = Post(postId)

  5. function render () {
  6.   console.log(`${post.title} for ${profile.name}`)
  7. }

  8. profile.listen(render)
  9. post.listen(render)
  10. render()
  11. ```

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.

  1. ``` js
  2. if (isServer) {
  3.   settings.set(initialSettings)
  4.   router.open(renderingPageURL)
  5. }
  6. ```

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

  1. ``` js
  2. import { allTasks } from 'nanostores'

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

  5. const html = ReactDOMServer.renderToString(<App />)
  6. ```

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.

  1. ```ts
  2. import { cleanStores, keepMount } from 'nanostores'
  3. import { profile } from './profile.js'

  4. afterEach(() => {
  5.   cleanStores(profile)
  6. })

  7. it('is anonymous from the beginning', () => {
  8.   keepMount(profile)
  9.   expect(profile.get()).toEqual({ name: 'anonymous' })
  10. })
  11. ```

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

  1. ```ts
  2. import { allTasks } from 'nanostores'

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

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.

  1. ```ts
  2. import { atom, onMount } from 'nanostores'

  3. export const currentTime = atom<number>(Date.now())

  4. onMount(currentTime, () => {
  5.   currentTime.set(Date.now())
  6.   const updating = setInterval(() => {
  7.     currentTime.set(Date.now())
  8.   }, 1000)
  9.   return () => {
  10.     clearInterval(updating)
  11.   }
  12. })
  13. ```

Use derived stores to create chains of reactive computations.

  1. ```ts
  2. import { computed } from 'nanostores'
  3. import { currentTime } from './currentTime.js'

  4. const appStarted = Date.now()

  5. export const userInApp = computed(currentTime, now => {
  6.   return now - appStarted
  7. })
  8. ```

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 where you
change this store.

  1. ```diff
  2.   const increase = action(counter, 'increase', store => {
  3.     store.set(store.get() + 1)
  4. -   printCounter(store.get())
  5.   }

  6. + counter.listen(value => {
  7. +   printCounter(value)
  8. + })
  9. ```

An action 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.

  1. ```diff
  2. - const { userId } = profile.get()
  3. + const { userId } = useStore(profile)
  4. ```

Known Issues


ESM


Nano Stores use ESM-only package. You need to use ES modules
in your application to import Nano Stores.

In Next.js ≥11.1 you can alternatively use the [esmExternals] config option.

For old Next.js you need to use [next-transpile-modules] to fix
lack of ESM support in Next.js.

[next-transpile-modules]: https://www.npmjs.com/package/next-transpile-modules
[esmExternals]: https://nextjs.org/blog/next-11-1#es-modules-support