State Management

Learn how to define state variables, manage their scope, and practice global state management using composables and Pinia.

A state can be thought of as any data structure stored in memory that holds information for a component or the entire application at a given time.

In the last lesson on rendering mechanism, one can infer that state management plays a key role in how Vue renders the templates on the DOM.

In this lesson, we will discuss how to define state variables and manage state variable scope.

Define state in a Vue component

Can a component state be defined using regular JavaScript variables, as shown below?

Press + to interact
<script setup>
const name = "";
const bio = {
height = 0,
age = 0,
sex = ''
}
</script>

We have discussed about reactivity and how Vue uses reactive state variables to control the rendering mechanism in a previous lesson. For this reason, it would not be possible to use regular variables because Vue would not be aware of any mutation (change) that can be made on this object. As such, the DOM would not be updated when a state change occurs.

In order to define a state, we need to use any one of the Vue reactive objects.

Therefore, the example above can be redeclared as follows:

Press + to interact
<script setup>
import { ref, reactive } from "vue";
const name = ref("");
const bio = reactive({
height = 0,
age = 0,
sex = ''
});
</script>

Localized state management

As shown in the illustration below, in localized state management, the state values are only used within the scope of the component it was created in. These state values can be passed down to ...