Skip to content
Bunshi
GitHub

Nanostores

Background

Nanostores is 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.

As an atomic state store, it shares a lot in common with jotai and Recoil.

Component state

Bunshi lest you re-use the power of nanostore atoms to build local state for your components, instead of only globally.

  • The multiplier uses global state
  • The counter uses component state
  • The value is derived from both local and global state
import { ComponentScope, molecule } from "bunshi";
import { atom, computed } from "nanostores";

export const MultiplierMolecule = molecule(() => atom(0));

export const CountMolecule = molecule((mol, scope) => {
  scope(ComponentScope);

  const countAtom = atom(0);
  const increment = () => countAtom.set(countAtom.get() + 1);

  const valueAtom = computed(
    [mol(MultiplierMolecule), countAtom],
    (mult, count) => mult * count
  );

  return {
    countAtom,
    valueAtom,
    increment,
  };
});

Global state

You can use nanostores to define global atoms shared across your application.

import { molecule } from "bunshi";
import { atom, computed } from "nanostores";

export const MultiplierMolecule = molecule(() => atom(0));

export const CountMolecule = molecule((mol, scope) => {
  const countAtom = atom(0);
  const increment = () => countAtom.set(countAtom.get() + 1);

  const valueAtom = computed(
    [mol(MultiplierMolecule), countAtom],
    (mult, count) => mult * count
  );

  return {
    countAtom,
    valueAtom,
    increment,
  };
});

Why Bunshi with nanostores?

Bunshi helps with scoping your atoms. It allows you to pull state up and push state down the component tree. If the only type of state you have is global state and it doesn’t need to be lazy, then you can avoid bunshi and use nanostores with global variables.

  • Start using nanostores for component-level state
  • Stick to the vanilla javascript API for nanostores
  • Decouple your nanostores logic from your UI framework code
  • Move your state from component level to global without refactoring components