·
2 min read

Vue Tip: Simple State Management With Composition API

Vue Tip: Simple State Management With Composition API Image

You might think that you need a state management library like Pinia to manage your state, but that's not always the case. If you have a small application that only needs to share state between a few components, you can use the Composition API to create a simple state management solution.

Build a Simple State Management Solution

Let me show you how you can build a simple state management solution with the Composition API which contains state, mutations/actions, and getters.

Let's start by defining the state using a reactive object inside a useState.ts composable:

useState.ts
const state = reactive({ counter: 0 }) export const useState = () => { return {} }

By lifting the state outside the composable function, it can be shared between multiple components. Read more at "Share Composable State Across Components".

Next, we need to define the mutations/actions that can update the state. All we need to do is to add a function that updates the state:

useState.ts
const state = reactive({ counter: 0 }) export const useState = () => { function setCounter(value: number) { state.counter = value } return { setCounter } }

For a getter, we can simply return the state:

useState.ts
const state = reactive({ counter: 0 }) export const useState = () => { const count = computed(() => state.counter) const doubleCount = computed(() => state.counter * 2) return { count, doubleCount } }

Info

Make sure to only return read-only state from your composable. A computed property is read-only by default but you can also use the readonly function provided by Vue.

Why Pinia?

You might wonder why you should use a store library like Pinia if you could just use the Composition API to build a simple state management solution. The answer is provided in Pinia documentation and here are some of the reasons. Pinia provides:

  • Devtools support
  • Hot module replacement
  • Plugins: extend Pinia features with plugins
  • Proper TypeScript support or autocompletion for JS users
  • Server Side Rendering (SSR) Support

StackBlitz

You can try our simple state management solution in the following StackBlitz:

If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.