DEV Community

Cover image for Vue is still the only framework capable of this
Michał Kuncio
Michał Kuncio

Posted on • Updated on • Originally published at michalkuncio.com

Vue is still the only framework capable of this

Mutating objects in Javascript

If you want to add a new item in pure Javascript all you have to do is:

const items = ['🍕', '🍟']
items.push('🍔')
Enter fullscreen mode Exit fullscreen mode

when you inspect the value of the items array you will see that the original array is mutated and the value is:

['🍕', '🍟', '🍔']
Enter fullscreen mode Exit fullscreen mode

Okay, but how does that kind of mutation work in reactive frameworks like React or Svelte?

Adding a new item to an array in React/Svelte

In React or Svelte the above solution won't work. That's because of how reactivity works in these frameworks. You can't directly mutate arrays by using native Array.prototype.push(). In both situations, you have to create a new copy of the current array, add the new item to that copy and then reassign the current array to the new copy:

React:

setFood([
    ...food,
    newFood
]);
Enter fullscreen mode Exit fullscreen mode

Svelte:

food = [...food, newFood]
Enter fullscreen mode Exit fullscreen mode

So, every time you want to mutate an array, you have to create a new copy and make a reassignment. These are really simple examples but it can quickly become cumbersome if you have nested arrays and objects.

Adding a new item to an array in Vue

In Vue, the native JS engine behavior just works as expected:

food.value.push(newFood.value);
Enter fullscreen mode Exit fullscreen mode

Maybe it doesn't look like a dealbreaker, but for me, this way is way more convenient and natural and the greater difference will be visible in the case of more complicated operations with a lot of updates, especially on nested arrays and objects. I love how clever the reactivity model in Vue is.

⭐ If you like my posts, please follow me on Twitter:
https://twitter.com/michalkuncio

Top comments (3)

Collapse
 
altrusl profile image
altrusl • Edited

I would add to this also that Vue 3 uses for reactivity JavaScript Proxy object that has native implementation in JS engines (like V8)
So it should be faster and more performant then custom reactivity of React, Svelte or Vue 2

Collapse
 
michalkuncio profile image
Michał Kuncio

I'm not sure about the performance point but keeping it close to how it works natively in JS engine thanks to Proxy Objects is definitely a good thing :D

Collapse
 
altrusl profile image
altrusl

Nice catch!