Shared state with Composition API

Published 
Vue

Very often there's a need to use some kind of shared state between parent and child components. You'd say - we have props and emits, yes, we do have them, but they're not for massive states. It would be cumbersome to pass data as prop, then emit() it from child to parent, and what if child is nested 3-4 levels down.

In a Vue 2 era it was possible to use mixins with a shared state, but it was clunky. Now when we got a Vue 3 and it's Composition API - we can achieve this very elegantly.

Create a shared state

useSharedState.ts:

const state = reactive({
  var1: null,
  var2: null,
  var3: null
})

export default function () {
  return {
    state
  }
}

Use shared state

Now we can use our shared state everywhere.

Parent.vue, Child.vue, GrandChild.vue:

<script setup lang="ts">
import useSharedState from './useSharedState'

const { state } = useSharedState()
</script>

Please note

One downside to this method - we can mutate state everywhere we use this state, so it might be not obvious. Use it wisely.