Lightning web component Life cycle
Lightning web components have a lifecycle managed by the framework. The framework creates components, inserts them into the DOM, renders them, and removes them from the DOM. It also monitors components for property changes.
A lifecycle hook is a JavaScript callback method triggered at a specific phase of a component instance’s lifecycle.
constructor()
Called when the component is created. This hook flows from parent to child. You can’t access child elements in the component body because they don’t exist yet. Properties are not passed yet, either.
connectedCallback()
Called when the element is inserted into a document. This hook flows from parent to child. You can’t access child elements in the component body because they don’t exist yet.
render()
Call this method to update the UI. It may be called before or after connectedCallback().
It’s rare to call render() in a component. The main use case is to conditionally render a template. Define business logic to decide which template (HTML file) to use. The method must return a valid HTML template.
For example, imagine that you have a component that can be rendered in two different ways but you don’t want to mix the HTML in one file. Create multiple HTML files in the component bundle. Import them both and add a condition in the render() method to return the correct template depending on the component’s state.
renderedCallback()
Called after every render of the component. This lifecycle hook is specific to Lightning Web Components, it isn’t from the HTML custom elements specification. This hook flows from child to parent.
A component is rerendered when the value of property changes and that property is used either directly in a component template or indirectly in the getter of a property that is used in a template.
Note
Do not use renderedCallback() to change the state of a component, such as loading values or setting properties. Use getters and setters instead.
Don’t update a wire adapter configuration object property in renderedCallback(), as it can result in an infinite loop.
Don’t update a reactive property or field in renderedCallback(), as it can result in an infinite loop.
errorCallback(error, stack)
Called when a descendant component throws an error. The error argument is a JavaScript native error object, and the stack argument is a string. This lifecycle hook is specific to Lightning Web Components, it isn’t from the HTML custom elements specification.
Let’s go through with the example
Please get the running code from my GitHub repository
https://github.com/ranbirdasgit/SF-LWC/tree/master/Lifcycle