I have posted a similar question on Salesforce stack where the context is Lightning Web Components(which is just an extension of HTML Web Components). I am asking here because I would like to reach a wider audience.
In their documentation they say that it is not recommended to get/set properties of a custom component in the connectedCallback() hook. Does anyone here know why would this recommendation be given, as I use this hook specifically for getting/setting properties.
There is no problem with reading or setting properties with connectedCallback
callback handler. The original guidelines has to do with the fact that props can change after connectedCallback
and this function is executed only when component is attached to the DOM tree. It means that your code will not be able to properly handle the reactivity.
It is not a technical constraint per se; it more like good architectural guidelines when dealing with web components.
General rule of thumb:
connectedCallback
for one time stuff like templates, setting up observations (ensure that observations are cleaned up in disconnectedCallback
.getters
and setters
for managing the property watchers. Also, do not handle async workflows within setters. Example Promise.then()
, etc. The reason for this is to properly handle the cancellation for already running requests when prop changes. Thus use observables preferably set in connectedCallback
.