Skip to content
Bunshi
GitHub

Valtio

Background

The Valtio API is minimal, flexible, unopinionated and a touch magical. Valtio’s proxy turns the object you pass it into a self-aware proxy, allowing fine-grained subscription and reactivity when making state updates.

As a proxy state store, it shares a lot in common with ref from Vue and MobX.

Component state

Bunshi lest you re-use the power of valtio proxies 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 { derive } from "derive-valtio";
import { proxy } from "valtio/vanilla";

export const MultiplierMolecule = molecule(() => proxy({ count: 0 }));

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

  const countProxy = proxy({ count: 0 });
  const increment = () => countProxy.count++;

  const multiplierProxy = mol(MultiplierMolecule);
  const valueProxy = derive({
    value: (get) => get(countProxy).count * get(multiplierProxy).count,
  });

  return {
    countProxy,
    valueProxy,
    increment,
  };
});

Global state

You can use valtio to define global proxies shared across your application.

import { molecule } from "bunshi";
import { proxy } from "valtio/vanilla";
import { derive } from 'derive-valtio'

export const MultiplierMolecule = molecule(() => proxy({ count: 0 }));

export const CountMolecule = molecule((mol, scope) => {
  const countProxy = proxy({ count: 0 });
  const increment = () => countProxy.count++

  const multiplierProxy = mol(MultiplierMolecule);
  const valueProxy = derive({
    value: (get) => get(countProxy).count * get(multiplierProxy).count,
  })

  return {
    countProxy,
    valueProxy,
    increment,
  };
});

Why Bunshi with Valtio?

Bunshi helps with scoping your atoms. It allows you to pull state up and push state down the component tree. Valtio has a guide on how to use useRef and useContext to create component state, but Bunshi makes the process more simple and your code more portable.

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