Vue.js is a well-known and efficient JavaScript framework used for front-end
Application development. Over time it has evolved a lot and focused on giving the best to its users. And it has done it successfully.
Lately, ‘Vue 3 Reactivity and Composition API’ has become the talk of the town. Why should I miss the chance of learning it and helping my readers know Reactivity in Vue 3 and explore Vue Composition API? Before hopping onto Vue 3 Reactivity, I would like to make you familiar with the programming concept of reactivity. I have ordered this blogpost for its simplification. What are we waiting for; let’s proceed.
Table of Index
2. Reactivity in JavaScript: What are the problem and its solution?
3. How is reactivity managed in ReactJS, AngularJS, and VueJS?
4. How reactivity works in Vue.js
5. Deep dive into Vue 2 Reactivity
What is Reactivity?
Being one of the best front-end developers, we all have used reactivity in one way or another, but do we know what does it mean actually? Are we aware of what is reactivity?
Many of us are not, and that’s okay! I’ll help you learn about reactivity through this blogpost. So, firstly, let me just define reactivity in the context of Front-end frameworks.
Reactivity can be defined as a phenomenon of updating the DOM (Document Object Model) automatically whenever the state of the application changes.
Pretty simple right?
This was the definition of reactivity; now, the problem is JavaScript is not reactive. Other JavaScript frameworks such as ReactJS, AngularJS, VueJS, and many more have their own engines for reactivity to monitor the application’s state changes.
Moving further to quench our curiosity regarding JavaScript Reactivity.
Reactivity in JavaScript: What Are the Problems and solutions?
I’ll be exemplifying you with a simple code of Adding two numbers to understand why Javascript is not Reactive and its problem.
The output of this code will be:
Now let’s change the value of number1 and see what happens.
Here’s the turning point.
You might expect the total to be updated but see the output below.
The output didn’t change. Isn’t it strange? Even after updating the value of number1, the output was the same. Before executing the line of console.log, the engine wasn’t aware of the state updation and thus showed the previous value of number1. Encountering this fact made me more curious to learn about how Javascript frameworks implement their own engines for reactivity? We will get back to this question later.
For making realize the engine about the updation of the value, you can do this –
Then the output would be as expected.
But this is quite annoying to repeat the logic every time the value gets updated. You can wrap the logic of calculating total inside a function and then re-run it like this.
This works too!
But, still, this is not a feasible thing to do. We shouldn’t call a function every time to indicate the updation of value. It seems easy in this example but thinks of managing 10 or 20 variables. How will you manage their internal complex relations? Will you make separate functions for managing its updation? Solving this problem of reactivity for a larger-scale seems challenging. Hopefully, the community has already come up with the solutions. The three major Javascript frameworks- ReactJS, AngularJS, and VueJS, have made reactivity possible and feasible! Let’s see how it works.
Want to develop a sustainable and high-performance VueJS application?
Bacancy has astute developers with high problem-solving skills and advanced VueJs knowledge. Contact us and hire Vue Js developer for your dream project.
How is Reactivity Managed in ReactJS, AngularJS, and VueJS?
ReactJS
Introducing a setState() function which can be used whenever the value of number1 is updated. Under the hood, the setState() function calls the render method and updates the DOM for displaying the value of total.
AngularJS
detectChanges() goes through every property and checks whether it has been updated since the last time or not. If it successfully encounters an updated property (here, number1), then it will update all the properties having the updated property (here, total) and then runs detectChanges().
VueJS
Use of getters and setters to the property being tracked. While tracking, if a tracked property is encountered, then the function that accessed that property will be identified as ‘subscriber.’ Every time the property is updated, every subscriber will be notified.
These are the various solutions found by the community of these frameworks. As this blogpost concerns Vue 3 Reactivity, I’ll be focusing the same. Now it’s time to gain more information and explore how the Reactivity in Vue evolved.
How Reactivity Works in Vue.js?
Let’s take a small example to understand Reactivity in Vue.
I have a Vue component consisting of one data property, say a message. And further, you’ll render this in the view.
Vue.component("demo-component", { data: { message: "Hello, world" }, template: "< span >{{ message }}< /span >" });
You’ll see this when the application starts.
< span >Hello, World< /span >
Now let’s see what happens on changing the message in some method.
methods: { onUpdateMessage () { this.message = "Message Updated!"; } }
Automatically, Vue will reflect this modification.
< span >Message Updated!< /span >
So, this how the Reactivity in Vue works. Reactive data causes the side effect whenever it gets updated.
Deep Dive into Vue 2 Reactivity
As we overviewed before, Vue 2 Reactivity uses getters and setters for making the data reactive. It walks through every data property declared by the user and pins it with getters and setters to be triggered whenever the data is changed. Though the view is changed quickly and smoothly, whenever the state is updated, Vue 2 Reactivity has a limitation – The Reactivity is applied automatically only when the application is instantiated. It means that the application won’t provide reactivity on adding a new property in the data object during the application lifecycle. The main reason behind this shortcoming is, when Vue 2 was designed, there was no proper way discovered to notice such modifications in Javascript.
Let me help you with a small code snippet.
const data = { id: 10, // reactive name: "New Item", // reactive }; Vue.component("new-item", { data }); data.price = 14.7 // non-reactive
Properties named id and name would be considered to be reactive as it was declared at the time when the application was instantiated. On the other hand, the property named price would not be reactive because it was declared after the application was instantiated. And, usually, such non-reactive data properties cause problems that are sometimes very difficult to debug.
Vue introduced API such as Vue to solve this problem set for adding reactive data after instantiation. So, if I want to make my data property price reactive, then I can use Vue.set like this –
Vue.set(data, "price", 14.7); // reactive data property
Though Vue has solved this problem, it still depends upon the developer to remember Vue.set as it’s not provided automatically. The other limitations of Vue 2 Reactivity are deleting data property and modifications in reactive arrays. I won’t be covering that, but you can read it here in the documentation.
I hope this helped to clear your doubts regarding the shortcoming of Vue 2 Reactivity. Now moving towards Vue 3 Reactivity.
Explore Vue 3 Reactivity
The first important fact about Vue 3 is that it has been re-written, and many improvements have been made to overcome the limitations of Vue 2. Vue 3 has used Proxy, a Javascript feature, for Vue 3 Reactivity.
The introduction of Proxies not only solved the shortcomings of Vue 2 Reactivity but it also provided reusing of the logic through Composition API.
You might be wondering what Proxies are? So, here is your answer-
They are considered a particular object used for wrapping other objects on which you want to have your observation and want to be aware of any operation performed during runtime.
Let’s take an example to have a better understanding.
let data = { msg : "Hello, there!" }; const demoProxy = new Proxy(data, { set (target, property, value) { target[property] = value; console.log(target); } }); demoProxy.msg = "Bye!"; // Console: { msg: "Bye!" }
Here I have one data object which needs to be reactive. For that, I’ll be using a variable demoProxy and declare a new proxy for wrapping up my data. Later, I’ll be declaring a set function that will catch all the operations applied and trigger the side effects. It is easy to observe the whole data object due to the application of proxy on it. So whenever you’ll add a new data property, it will be reactive.
demoProxy.newprop = null; demoProxy.newprop = "new" // console: { msg: "Bye!", newprop: "new" }
The user can not see the proxied object used under the hood. But they are capable of performing tracking of dependency and notifying the changes whenever the modifications are done.
You must know that the proxied object is NOT EQUAL to the original object.
const originalObj = {} const wrappedObj = new Proxy(originalObj, handlers) console.log(originalObj === wrappedObj) // false
The originalObj and wrappedObj may behave the same most of the time, but whenever there’s a need to compare them strictly, like in .filter() or .map(), it will fail to give expected outputs.
You May Also Like To Read: How to Build To-do App with Vue 3 Typescript
Introduction to Vue Composition API
Vue 3 allows us to define components in another via Composition API. Using Vue Composition API, we can declare the setup’s features rather than declaring them as options.
While using Vue 3 Composition API, we can create reactive data using the new reactive API
import { reactive } from "vue"; export default { setup () { const data = reactive({ msg: "Hello, there" }); // do other stuff here... return { data } } }
As you can see above, I have declared a reactive data object inside the setup function. Some logic to be done with that data object, leaving it up to you. For making it available to the template, just return the data object. You can check the documentation for all other features of the Composition API. Let’s focus on what can be done with reactive data before it is returned. Vue Composition API allows us to use the data objects more flexibly than before because it will enable creating objects, not bounded to context object (this). However, reactive API and Composition API’s primary goal is to widen the scope of reactive data usage and share it between reusing logic components.
There are many more possibilities associated with Vue 3 Reactivity. As it has decoupled the implicit implementation of reactivity into public APIs such as reactive and ref ( other new and advanced features: Advanced Reactivity APIs), there’s a lot more to explore and learn about it. The Composition API allows holding an excellent grip in Vue 3 Reactivity. The concept of reactivity is roughly the same as Vue 2, and the optional features of Vue 3 won’t get into your way of learning it.
Having said that, all I hope this blog post has helped you clear your doubts about Reactivity in Javascript, its frameworks, and Vue 3 Reactivity.
Conclusion
If you are not sure about how to use Vue composition API and looking for a helping hand to get the job done by making your product’s code more maintainable and readable, Bacancy is the best Vue.js development company offering dedicated and skilled VueJS developers to build high-performance applications. Our Vue.js developers are well-versed at using Vue composition API and to make your application more scalable as well as reusable across several components.