On this page
On this page
Getting started
A store is a plain JavaScript module. Components only read it.
Install
Section titled “Install”npm install nanostoresCreate a store
Section titled “Create a store”atom keeps one value. Actions that change it are plain functions next to the store.
import { atom } from 'nanostores'
export interface User { name: string isAdmin: boolean}
export const $users = atom<User[]>([])
export function addUser(user: User) { $users.set([...$users.get(), user])}Derive a value
Section titled “Derive a value”computed recalculates when the stores it depends on change.
import { computed } from 'nanostores'import { $users } from './users'
export const $admins = computed($users, (users) => users.filter((user) => user.isAdmin),)Read it in a component
Section titled “Read it in a component”Install the adapter for your framework. The component re-renders when $admins changes.
npm install @nanostores/reactimport { useStore } from '@nanostores/react'import { $admins } from '../stores/admins'
export function Admins() { const admins = useStore($admins) return ( <ul> {admins.map((user) => ( <li key={user.name}>{user.name}</li> ))} </ul> )}npm install @nanostores/vueimport { useStore } from '@nanostores/vue'import { $admins } from '../stores/admins'
const admins = useStore($admins)Use admins in the template as a regular ref.
No adapter needed: subscribe calls the callback right away and on every change.
import { $admins } from '../stores/admins'
const list = document.querySelector('#admins')!
$admins.subscribe((admins) => { list.replaceChildren( ...admins.map((user) => { const item = document.createElement('li') item.textContent = user.name return item }), )})Svelte, Solid, Lit, Angular, Alpine.js and Web Components: see Frameworks.
- Lazy stores: load data only while a component listens.
- Move logic from components to stores
- API reference