Skip to content
On this page

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.

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.

import { cleanStores, keepMount } from 'nanostores'
import { $profile } from './profile.js'
afterEach(() => {
cleanStores($profile)
})
it('is anonymous from the beginning', () => {
keepMount($profile)
// Checks
})

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