Lifecycle Hooks in Lightning Web Components

Updated: Apr 17, 2020

In Aura framework init(), render(), rerender(), afterRender(), unrender() methods were used to handle the lifecycle of components. Similarly, Lightning web components have callback method, that are used to handle lifecycle of the components. These are called lifecycle hooks. You can override these hooks to modify the behavior.

1. constructor() -Constructor fires when a component instance is created, it is similar to init() method of aura component.

Do not assign any property in Constructor because they are not ready at this point.The flow of Constructor is flows from parent to child (init flows from child to parent), so do not try to access child element. It means if there are child components in LWC, then first parent constructor will be called, followed by child constructor.

import { LightningElement } from 'lwc';
export default class App extends LightningElement {
    constructor() {
        console.log('In Constructor');

2. connectedCallback() -

This method fires when component inserted into DOM, and it can fire more than one time.This hook fires from parent to child. You can’t access child elements in the component body because they don’t exist yet.Parent element can be modified in this hook

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {