State Management Using Vue 3.x Reactivity API
A Vue
component––in a traditional sense––consists of:
- an action
- a state, and
- a view.
If a Vue
component was a room, then the state
of that component would be represented by the number of people in that room, temperature and air humidity.
To reduce the population, anyone of those people would have to, existentially, walk out of the room. If the temperature is, unbearably, high, the window could be open to allow more air in.
Do you see the pattern?
To control the state of the room––number of people
––some of the people in the room will have to perform the action
of, empirically, walking out of the room. In the same vein , for a Vue component, it takes an action
(method) to mutate a state
(an attribute) that will be, subsequently, presented on a view
.
<script setup>
import { reactive } from 'vue'
// state
const todos = ref([])
// actions
function add(todo) {
todos.push(todo)
}
</script>
<!-- view -->
<template>
<ul>
<li
v-for="(todo, index) in todos"
:key="index"
v-text="todo"
/>
</ul>
</template>
The state
, actions
and view
of a component, collectively, represent the concept of "one-way data flow". In a real sense, all instances of a Vue component manage their own reactive states. Nevertheless, in a real-world application, two or more components might need to share or mutate the same piece of data(state).
To tackle a situation like that, such state can be lifted up to a parent component and passed down to child components as props––an approach that has, oftentimes, led to a problem known as prop drilling
.
Another––widely used––approach is to mutate and synchronise multiple copies of the state using emitted events
. Solves the problem of prop drilling
but, still, coarse
and fragile
––It's a free-way to unmaintainable code.
Vue 3.x's Reactivity API
presents us with a simpler and straightforward approach.
Instead of state-lifting or mutating and synchronising via emitted events, what if we just abstract the state into it's own module. Then, import it into any component that wants to use it. That way we can conveniently and independently manage the state away from any kind of noise.
Sounds interesting? Read more about it in the official documentation.