Javascript is required
ยท
1 min read

Vue Tip: Share Composable State Across Components

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