Javascript is required
Michael Hoffmann LogoMichael Hoffmann

Vue Tip: Share Composable State Across Components

Michael Hoffmann - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Oct 28, 2022
1 min read
|
1360 views
Composables
Vue Tip: Share Composable State Across Components Image

We create a new state on each function call if we define state in a Vue composable. But sometimes, we want to sync the composable state across components.

Let's take a look at a simple example:

useCart.ts
1
import { Ref, ref } from 'vue'
2
3
const useCart = () => {
4
const cart: Ref<Record<string, number>> = ref({})
5
6
const addToCart = (key: string, value: number) => {
7
cart.value[key] = value
8
}
9
10
return {
11
cart,
12
addToCart,
13
}
14
}
15
16
export default useCart

We define a simple reactive variable cart inside the useCart composable. Every time a component calls useCart, a new state is created.

The following Stackblitz includes a running demo. Click "Add to cart" on "Component 1" and "Component 2", and you can see that every component has it's own cart state:

To keep the same state between every useCart instance, we need to lift he state up outside the function, so it's created only once:

useCart.ts
1
import { Ref, ref } from 'vue'
2
3
const cart: Ref<Record<string, number>> = ref({})
4
5
const useCart = () => {
6
const addToCart = (key: string, value: number) => {
7
cart.value[key] = value
8
}
9
10
return {
11
cart,
12
addToCart,
13
}
14
}
15
16
export default useCart

You can test it by yourself in the Stackblitz demo above: Click "Add to shared cart" on "Component 1" and "Component 2", and you can see that they now share the same state.


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

New Vue & Nuxt tips delivered to your inbox:
I will never share any of your personal data.