How to handle reactivity in VueJs

How to handle reactivity in VueJs

Reactivity in VueJs explained

One of the distinct features of single-page application frameworks and libraries like Vue is the inbuilt reactivity functions. Reactivity is important as it helps prevent hot reloads to handle state change in an application.

Before we go on;

Prerequisite

  • Know HTML and Javascript, also an intro knowledge to Vue

  • Have a vue app running locaaly on your machine

  • You are expected to follow through and test each example in this article to grasp the concept

What is Reactivity?

The term "reactivity" is commonly used in the world of programming these days, but what exactly is it?

Reactivity is a phenomenon that occurs when individuals alter their performance or behavior due to the awareness that they are being observed.

With the above analogy, let's relate it to programming. Simply put, reactivity is a programming paradigm that allows us to adjust to changes in a declarative manner. Reactivity solely relates to changes, say mutation.

Vue 3 came with a lot of reactivity options, below are some of the options available

  1. ref

  2. reactive

  3. Template ref

  4. toRef

  5. toRefs

  6. unref

Let's discuss the above;

ref

ref is needed to update your data. Without ref, a declared value can not be mutable. A ref can be a primitive data type or even an object.

As an example to demonstrate ref in action, here is an example of a message being declared and updated in a function at the click of a button. Notice that when the ref is taken off, the message value is immutable - try it out.

<script setup>
import { ref } from "vue";

let message = ref("Hello World")

const updateMessage = () => message.value = "Updated Text"
</script>

<template>
    <div>
        <p>{{ message }}</p>
        <button @click="updateMessage">Update Text</button>
    </div>
</template>

reactive

Vue's reactive can work with objects, arrays and primitives. The following code shows reactive in action. We can manipulate the age property in the person object because the person object is wrapped by reactive.

<script setup>
import { reactive } from "vue";

let person = reactive({name: "Micheal", age: 20})

const updatePersonAge = () => person.age += 1
</script>

<template>
    <div>
        <p>{{ person.age }}</p>
        <button @click="updatePersonAge">Update Person Age</button>
    </div>
</template>

Template ref

in Options API(Application Programming Interface), we have access to refs using this object. Vue stores all template refs under the property this.$refs. In contrast, the new Vue 3 Composition API allows us to reference the template ref by declaring a ref value in the script. The ref has a default value of a string and will be the value of the input once our component is mounted, in this case <button>press me</button> .

Template ref comes in handy when you want to manipulate an element using javascript, pass a reference to an element as a prop or change the inner test of an HTML element.

<script setup>
import { ref } from "vue";

const button = ref("");

const changeButtonText = () => console.log(button.value);
</script>

<template>
    <div>
        <button ref="button" @click="changeButtonText">press me</button>
    </div>
</template>

toRef

the toRef is used to convert a reactive object to a ref. toRef converts a single reactive object property to a ref that maintains its connection with the parent object.

<script setup>
import { reactive, toRef } from "vue";

const person = reactive({name: "Micheal", age: 20, height: "1.75m"})

const name = toRef(person, "name");
const age = toRef(person, "age");
const height = toRef(person, "height");
</script>

<template>
    <div>
        <p>{{ name }}</p>
        <p>{{ age }}</p>
        <p>{{ height }}</p>
    </div>
</template>

toRefs

toRefs converts all the properties of an assigned reactive value to a plain object with properties that are refs.

In this example, we destructure the person object and coverts its properties with toRefs which makes it accessible and visually makes the code readable.

<script setup>
import { reactive, toRefs } from "vue";

const person = reactive({name: "Micheal", age: 20, height: "1.75m"})

const {name, age, height} = toRefs(person);
</script>

<template>
    <div>
        <p>{{ name }}</p>
        <p>{{ age }}</p>
        <p>{{ height }}</p>  
    </div>
</template>

unref

Though not popularly used, it is used to get rid of the .value attached when accessing a ref value. In our template interploation, we can access the count value by just printing out count.

<script setup>
import { ref, unref } from "vue";

let count = ref(1)

const multipleOfCountByTen = () => count.value = unref(count) * 10
</script>

<template>
    <div>
        <p>{{ count }}</p>
        <button @click="multipleOfCountByTen">Multiply</button>
    </div>
</template>

Conclusion

Reactivity is at the core of a single-page application as updates are to be made from time to time without having to reload an entire frame. Vue gives you a range of options that suits your specific purpose at the time. We've successfully used some of the available reactivity options provided by vue in this article. I hope this article has provided some clarity on how to handle reactivity in your vuejs applications.

Happy coding!

Find more on how Vue Reactivity works under the hood here.