do component property defaults need to be set in init hook?


#1

We use Ember at my work and I’ve noticed a new trend on code reviews from other developers that all default values need to be set in the init hook with setProperties instead of just setting the property directly on the component. This seems like it is unneccessary and adds more code lines vs just adding val:default_value to a component. I can’t find any evidence that properties should be set in init. I’m pretty sure this only applies to mixins and reference based values like arrays. So, are there any benifits to setting component property default values in the init hook vs just straight on the component?

    Component.extend({
        prop: 'default_value'
    });

vs

Component.extend({
    init(){
        this._super(...arguments);
        this.setProperties({
            prop: 'default_value'
        });
    }

});


#2

No benefit, it seems unnecessary. Like you said, I only use init for reference values.


#3

There are cases where it does make sense, for example if you are setting anything that is itself a mutable object and you do it in Component.extend({}) vs init you are likely to have created a memory leak…

See https://github.com/ember-cli/eslint-plugin-ember/blob/master/docs/rules/avoid-leaking-state-in-ember-objects.md for more details…


#4

These are saying the same thing:

So yeah, I agree that @Leonardo_Merza is correct and people are being unnecessarily strict by saying you must always use init.