LWC Lifecycle Hooks
A lifecycle hook is a callback method triggered at a specific phase of a component.
61. What is the use of the constructor method in LWC?
constructor method gets called when the component instance is created. This method also flows from parent to child, which means that it fires in the parent first. You can’t access child elements because they don’t exist yet. Properties are assigned to the component after construction and before the connectedCallback() method execute.
connectedCallback method is called when the element is inserted into a document. This method flows from parent to child. You can’t access child elements because they don’t exist yet. connectedCallback is used with the initial properties passed to the component, fetch data, set up caches, or listen for events.
The connectedCallback() can fire more miltiple times.If you remove an element and then insert it into another position, such as when you reorder a list, the connectedCallback fires several times.
63. What is the use of the renderedCallback method in LWC?
The renderedCallback() is Use to perform logic after a component has finished the rendering phase. This hook flows from child to parent.
64. What is the use of the render method in LWC?
It's used to display the element in UI. It may be called before or after connectedCallback(). The main use purpose 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.
65. What is the use of the disconnectedCallback method in LWC?
disconnectedCallback method get's called when the element is removed from a document. disconnectedCallback hook flows from parent to child. Use disconnectedCallback() method to clean up work done in the connectedCallback() method, like purging caches or removing event listeners.
66. What is the use of the errorCallback method in LWC?
errorCallback(error, stack) Called when a descendant component throws an error.
67. How to stop executing the method multiple times?
A component is usually rendered many times during the lifespan of an application. To use renderedCallback hook to perform a one-time operation, use a boolean field like hasRendered to track whether renderedCallback() has been executed. The first time renderedCallback() executes, perform the one-time operation and set hasRendered = true. If hasRendered = true, don’t perform the operation.
68. How to check Component connected to the DOM?
We can use this.isConnected to check whether a component is connected to the DOM or not.