In this topic, we will discover life cycle hooks are used in Lightning Web Component (LWC)
Lifecycle hooks
its a callback method triggered at specific phase of component lifecycle.
Types
- constructor()
- connectedCallBack()
- renderedCallback()
- disconnectedCallBack()
- errorCallBack()
Flow of Lifecycle hooks
First it called parent constructor then parent connectedCallBack and then if there is any child component then it moves to child constructor -> connectedCall Back -> renderedCallBack then it moves to parent renderedCallback
constructor()
- Invoked when the instance of the component is created (similar to init() in aura).
- Fired in the parent component first since it flows from parent to child.
- You have to call super() inside first to call parant class constructor ie. LightningElement.
- access element in the component template, use this.template.
connectedCallback()
- Invoke when component inserted into DOM.
- It flows Parent to Child.
- Used for to perform initialisation task such as fetch data, set up cache, listen events.
- To check component is connected in DOM, use isConnected method.
disconnectedCallback()
- Called when the element is removed from a document (remove event listener, remove time interval etc).
- Follows Parent to Child.
- Use disconnectedCallback() to clean up work done in the connectedCallback(), like removing event listeners.
- You can also use this hook to unsubscribe message channel.
renderedCallback()
- Use it to perform logic after a component has finished the rendering phase. It invoked when a component is completely rendered on UI.
- Flows from child to parent component.
- Component rendered many times during there lifecycle, to track renderedCallBack(), use isRendered boolean field.
- Property leads to infinite loop in renderedCallBack().
errorCallback()
Implement it to create an error boundary component that captures errors in all the descendent components in its tree.
It captures errors that occur in the descendant’s lifecycle hooks or during an event handler declared in an HTML template.
- Called when a descendant(Child) component throws an error.
- Two arguments are passed in errorCallback(error,stack), the error argument is a JavaScript native error object, and the stack argument is a string.
Follow me on linkedIn and Twitter for such more related post
Comments
Post a Comment