Skip to content
Bunshi
GitHub

Vue Reactivity APIs

Background

Vue 3 introduced the composition API that includes reactive building blocks like ref, shallowRef and reactive. These primitives can be used for local or global state.

Since these are based on Proxy objects, they have a lot in common with Valtio.

Component state

You can use Vue’s reactivity API for different types of state using Bunshi. This example is based on the Vue developer docs for state management.

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

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

export const CountMolecule = molecule((mol, scope) => {
  const countRef = ref(0);

  const multiplierRef = mol(MultiplierMolecule);
  const valueRef = computed(() => countRef.value + multiplierRef.value);

  return {
    countRef,
    valueRef,
  };
});

Global state

In this example we made the counter state global. We removed the scope call, and now the state is global.

import { ComponentScope, molecule } from "bunshi";
import { computed, ref } from "vue";

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

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

  const countRef = ref(0);

  const multiplierRef = mol(MultiplierMolecule);
  const valueRef = computed(() => countRef.value + multiplierRef.value);

  return {
    countRef,
    valueRef,
  };
});

Why Bunshi with the Vue reactivity API?

Bunshi helps with scoping your state to the right level. It allows you to pull state up and push state down the component tree. If the only type of state you have is component state, then you can avoid bunshi and use the Vue reactivity API directly inside of your tree.

  • Use Vue’s reactivity API for global-level state
  • Stick to the reactivity API for all your state needs
  • Decouple your state logic from your UI components
  • Move your state from component level to global without refactoring components