How to make an object reactive in LWC

By default all the properties in LWC are reactive apart from objects. Let's see how to make objects reactive in LWC.

By default all the properties are reactive in LWC, as in, once a property is created and used in a template file, when the content of the property is changed, the modified data gets reflected in all the places it is used (this behaviour is valid only when the property is used in the template file).

Let me take an example and explain what does @track do.

There is an object person and this is the content of the object.

person = {
    name: 'Krishna Teja',
    profession: 'Salesforce',
    location: 'world'
}
declaring a property in controller file

By default this property is not reactive when I try to change the content of the property (though it is used in the template file).

When I change the content of the object like this, the new value is not reflected in the template file.

person.name = 'Teja'
mutating one of the keys of the object
name is not updated in the template though we assign a new value

That is because, the object is by default reactive when I try to change the complete content of the object like this.

person = {
    name: 'John Doe',
    profession: 'Python',
    location: 'Mars'
}
Am assigning a complete new definition to the object. 

Here am not just updating the value for one of the keys of the object, rather am assigning new definition to the object.

This is how the template file is going to be

<template>
    {person.name}
    <lightning-button label="Click Here" onclick={handleClick}></lightning-button>
</template>
This is the template file

If that is not what you need and if you want the object to be reactive even if one of the values for the key is changed, then we would need @track.

@track
const person = {
    name: 'Krishna Teja',
    profession: 'Salesforce',
    location: 'world'
}
using @track in the contoller file

In the object above I have used @track decorator, because of this, when I make a small change to one of the keys of the object as shown below.

person.name = 'John Doe'
mutating one of the keys of an object that has @track decorator

The object becomes reactive and the updated value gets displayed to the user on the template.

The updated name is refelcetd in the template file

See Ya!