Vue Tip: Simple State Management With Composition API
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:
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:
For a getter, we can simply return the state:
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:
Vue Tip: Manually Stop Watcher
You need to manually stop your Vue watcher if they are created asynchronously. Sync watchers are automatically stopped when the component is unmounted.
Nuxt Tip: An URL Object Working on Both Server-Side and Client-Side
Nuxt provides a helper function called useRequestURL that returns an URL object working on both server side and client side.