Web Analytics
  • Culture
      Back
      Agile Mindset

      Agile is not a principal or a method, but it’s an integral part of being Agile that is guided by principles, defined by values and manifested through various practices.

      Bacancy Values

      You add value to your customer when you deliver a product or service that has been designed specifically to solve their problem.

      Bacancy Culture

      Core Team will work as Scrum Team where Team will have quarterly goal to make sure that we run financial, administrative and project management prospective.

  • What we do
      Back
      Product Engineering

      Seize the opportunity to make your product stand out. We enable our clients

      AI & ML

      We automate businesses and optimize processes by deploying smart AI and...

      Blockchain

      Get a full spectrum of blockchain development services from us to bring scalability...

      IOT

      Improve Business Productivity and Efficiency using our high-end IOT professional services...

      Digital Transformation

      We truly become a part of your business by helping you think through the...

  • Who we work with
      Back
      Real Estate

      We can help you uncover the hidden revenue opportunities to showcase your...

      Finance & Insurance

      In the emerging technological environment, we are offering reliable banking and financial...

      Oil & Gas

      Reshape your energy landscape and gain better control by harnessing the best...

      Healthcare

      Utilizing advanced technologies to provide best software, web & mobile development services...

      Travel & Transport

      Manage your logistics and transportation business at the ease of your fingertips...

      Startups

      We can help you to build your MVP with advanced technologies....

  • About Us
      Back
      About

      Agile, A Process Delivering Values & Successful Products

      Blog

      Abstract Technology News Driven by Sources

      Career

      If you are passionate about your career, have creative flair and good craft skills, we want you!

  • Technology
      Back

      Front-End

      AngularJS ReactJS Vue.JS JavaScript Backbone.JS Ember.JS MEAN MERN

      Back-End

      Ruby on Rails Node.JS Golang Laravel PHP Python .NET Yii

      Mobile

      Android iOS React Native Flutter Ionic Kotlin

      CMS & CRM

      Spree Magento Wordpress Drupal Umbraco Woocommerce Salesforce Microsoft Dynamics 365<
      Explore All
  • Talk to Us
Talk to Us
Close
    MENU
  • Culture
    • Agile Mindset
    • Bacancy Values
    • Bacancy Culture
  • What we do
    • Product Engineering
    • AI & ML
    • Blockchain
    • IOT
    • Digital Transformation
  • Who we work with
    • Real Estate
    • Finance & Insurance
    • Oil & Gas
    • Healthcare
    • Travel & Transport
    • Startups
  • About Us
    • About
    • Blog
    • Career
  • Technology
      Front-End
    • AngularJS
    • ReactJS
    • Vue.JS
    • JavaScript
    • Backbone.JS
    • Ember.JS
    • MEAN
    • MERN
    • Back-End
    • Ruby on Rails
    • Node.JS
    • Golang
    • Laravel
    • PHP
    • Python
    • .NET
    • Yii
    • Mobile
    • Android
    • iOS
    • React Native
    • Flutter
    • Ionic
    • Kotlin
    • CMS & CRM
    • Spree
    • Magento
    • Wordpress
    • Drupal
    • Umbraco
    • Woocommerce
    • Salesforce
    • Microsoft Dynamics 365
    • Explore All
  • Contact Us
  • CLOSE
Vue 3 Reactivity

Let’s Explore the State of Vue 3 Reactivity, JavaScript Reactivity and Composition API

Archita Nayak
Archita Nayak Technical Writer
January 8, 2021 9 min read

Last Updated on March 2, 2021

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

1. What is Reactivity

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

6. Explore Vue 3 Reactivity

7. Introduction to Vue Composition API

8. Conclusion

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.

simple code of Adding two numbers

The output of this code will be:

total of numbers

Now let’s change the value of number1 and see what happens.

change the value

Here’s the turning point.

You might expect the total to be updated but see the output below.

total of numbers

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 –

updation of the value

Then the output would be as expected.

output

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.

 logic of calculating total

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.

Hire Vue 3 Developer

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-

The Proxy object enables you to create a proxy for another object, which can intercept and redefine fundamental operations for that object.

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.

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, then get in touch with us to hire dedicated Vue.js developer. 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.

Archita Nayak
Archita Nayak View all post
Writer. Developer. Dreamer. Believer. Achiever. My curiosity leads me to learn various technologies, and my love for writing helps me to impart my knowledge for the same. When I am not exploring technologies, I am mostly reading and writing poetry and fictional stories.

Expand Your Digital Horizons With Us.

Start a new project or take an existing one to the next level. Get in touch to start small, scale-up, and go Agile.


Or
E-mail us : [email protected]

Your Success Is Guaranteed !


Related articles
Vue js Large Application Structure
Vue.JS
How to Optimize the Performance of Vue js Large Application Structure?
February 10, 2021 by: Archita Nayak
Vue Storefront
Vue.JS
Introduction to Vue Storefront: Headless PWA to Boost Your eCommerce Site Performance
November 11, 2020 by: Paridhi Wadhwani
New Features in Vue 3
Vue.JS
What’s New in Vue 3? – A Comprehensive Overview on Exciting New Features in Vue 3
October 13, 2020 by: Kiran Bhatt

Top 1% IT Talent

Bacancy Technology is an exclusive hub of top dedicated software developers, UI/UX designers, QA experts, and product managers with an incredibly rare and hidden talents you will ever come across. We let you access the top 1% IT talent from independent software developers to the fully managed teams.

Time Zone Aligned

Timezone is never a constraint when you are working with Bacancy Technology. We follow one very simple principle – our developers and your time zone. Hire dedicated software developers from us and make collaboration in a faraway to work according to your time zone, deadline, and milestone.

Experienced Team

Whether you are looking for skilled developers in emerging technologies or looking for an extended arms to augment your existing team, we can lend a helping hand in both situations. We are a full-stack software development company with 300+ skilled and experienced software developers whom you can hire at your convenience to address the ongoing business challenges

Let us help you build a modern digital business to overcome traditional culture and succeed in the age of digital transformation.

  • USA
  • Canada
  • Australia
  • India
  • UAE
  • Sweden

USA

Bacancy Technology LLC

Florida

4995 NW 72nd Ave, Suite 307 Miami, FL 33166

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Canada

Bacancy Technology Inc

Toronto

71 Dawes Road, Brampton, On L6X 5N9, Toronto

Phone

+1 416 907 6738

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Australia

Bacancy Technology

South Australia

351A Hampstead Rd, Northfield SA 5085

Phone

(02) 8005 8222

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

India

Bacancy Technology Pvt Ltd

Ahmedabad

1207-1210, Time Square, Thaltej-Shilaj Road, Ahmedabad

Pune

2nd Floor, Marisoft-1, Marigold IT Park, Pune

Phone

079- 40037674

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

UAE

Bacancy Technology

Dubai

1608 Clover Bay, Business Bay, Dubai, UAE. PO Box 62049

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

Sweden

Bacancy Technology

Hagersten

Junkergatan 4, 126 53 Hagersten

Phone

+1 347 441 4161

Email

[email protected]

We guarantee 100% security of your information. We will not share the details you provide above with anyone. Your email won't be used for spamming.

How Can We Help?

  • Employee
  • Brochure
  • Quality Assurance
  • Resources
  • Privacy Policy
  • Sitemap
  • Solution
  • Contact Us
DMCA.com Protection Status
Request A Free Consultation