Search code examples
javascriptsalesforcesalesforce-lightninglwc

Declaring field public vs private with public accessor lwc child component


I need to pass a parameter from the parent component to a child in lwc. Is there a difference between having the field to be public vs private with a public accessor?

// Private field with public getter
import { LightningElement, api, track } from 'lwc';

export default class TodoItem extends LightningElement {
    @track 
    _itemName = 'New Item'; 

    @api
    get itemName() {
        return this._itemName;
    }

    set itemName(value) {
        this._itemName = value;
    }
}

vs

//Public accessor
import { LightningElement, api, track } from 'lwc';

export default class TodoItem extends LightningElement {
    @api 
    _itemName = 'New Item'; 
}

Solution

  • In LWC recommended will be:

    //Public accessor
    import { LightningElement, api } from 'lwc';
    
    export default class TodoItem extends LightningElement {
        @api 
        itemName = 'New Item'
    }
    

    P.S: the track decorator is now useless

    Like all fields as of Spring ’20, they’re reactive