Hello Friends, in this chapter we will learn about renderedcallback() in detail.
renderedCallback() is unique to Lightning Web Component. DOM is created after the connectedCallback and before the renderedCallback. renderedCallback() method is called after render() method.
This method is invoked when component is completely rendered,Basically when all the elements on the component are inserted. This method called is after every render of the component. This hook flows from child to parent.
As this method called after every render of the component, so we need to be careful, if we want to perform some operation is specific conditions like performing one time operation, use a private boolean property like hasRendered to track whether renderedCallback() has been executed.
Sample
import { LightningElement } from 'lwc'; export default class app extends LightningElement { renderedCallback() { // the required business logic to be executed when component is rendered } }
Example: Input Element to Understand renderedCallback()
app.html
<template> <lightning-input label="Name" onchange = {handleChange}> </lightning-input> {greeting} </template>
app.js
import { LightningElement} from 'lwc'; export default class App extends LightningElement { greeting; renderedCallback(){ console.log('renderd Callback'); } handleChange(event){ this.greeting = event.target.value; } }
If we place the above component in lightning page and check the console log, we will find that renderedCallback() gets fired multiple times.
Demo
hasRendered
Use hasRendered hook to perform a one-time operation, we can use a private boolean property like hasRendered to track whether renderedCallback() has been executed.
app.js
import { LightningElement } from 'lwc'; export default class App extends LightningElement { greeting; hasRendered = true; renderedCallback(){ if (this.hasRendered) { this.greeting = 'set by renderedCallback'; console.log('greeting ' + this.greeting); this.hasRendered = false; } } handleChange(event){ this.greeting = event.target.value; } }
I hope you enjoyed the chapter!
Together we can learn faster !
Join LWC study group on Telegram
Subscribe to Youtube channel and blog to get latest updates
Reference
Run Code when component renders