Member-only story

How To Destructure Props In Vue 3 Without Losing Reactivity

Nicky Christensen
5 min readFeb 20, 2023

--

If you have been working with Vue 3, you will know that if you destructure props, you will lose reactivity which can be a problem and lead to unexpected issues in your application. Not that long ago, I wrote an article about this which you can read here.

In Vue 3, passing data between components is done through props. When a component receives props, you can destructure them to access the individual pieces of data. However, if you’re not careful, destructuring props can cause the reactivity system in Vue to break as mentioned. In this article, we’ll explore why this happens and how to destructure props in a way that will preserve reactivity.

Why Destructuring Props Can Break Reactivity

Vue’s reactivity system is based on proxies and relies on the fact that it can track which properties of an object are accessed and when they are changed. When a component receives an object as a prop, Vue sets up a reactive getter and setter for each property of that object. This allows Vue to detect when a property is changed and update the component accordingly.

However, when you destructure an object prop, what you are doing is in its essence creating a new object that is no longer reactive. This is because the reactive getters and setters that Vue created for the original object do not transfer over to the new object. As a result, changes made to the destructured object will not trigger reactivity updates. If you are not aware of this as a developer, you will most likely experience unintended bugs and side effects in your application.

How To Destructure Props Without Breaking Reactivity

To destructure props in Vue 3 without losing reactivity, you can use the toRefs function. toRefs takes an object and returns a new object where each property is a ref. A ref is a reactive object that contains a single value.

--

--

Nicky Christensen
Nicky Christensen

Written by Nicky Christensen

Staff Software Engineer@Harness - A danish guy who speaks about frontend, tech & leadership - Follow & connect @ https://www.linkedin.com/in/dknickychristensen/

Responses (1)