top of page
Writer's pictureSaurabh Singh

renderedCallback in LWC

From the documentation, we know that renderedCallback method is called when component is completely rendered and it can be called multiple times. So if we want to perform any operation after rendering, we would put that code inside renderedCallback.


But still, what are those situation where we want to put any code inside renderedCallback.

checkout, below code.


Here in html, there are two buttons and button click, a function 'buttonClicked' will be called

and there is a input field which is inside a condition.


in Javascript code, on button click, we are retrieving it's label, setting a Boolean variable to true to show content inside if condition and setting the input fields value based on button labels.


Above code seems to be fine and should work right?

Wrong, above code will throw an error at line number 10.

why? because we are setting input fields variable but this field is not yet available in dom right now. Yes, we are setting Boolean variable true to show field but still it is not yet rendered in dom yet.


if you understood my point above, then you should have figured out that, we can set input field's value only when it is available in dom.


So, the solution is renderedCallback, now we know we can make use of it, because it will be called only after the component is completely rendered.


Now, check this modified code.



Here, we commented the error line and added a renderedCallback method, your code in renderedCallback method should be well conditioned, so that there not call every time there is a update on page.

So here, I took a Boolean variable to check when to show updated value on input field.


This code may not be the best example, but remember you will soon stuck where you need to fetch or set some fields, which are not yet rendered on the dom, so you will put your code inside renderedCallback, so prevent any error.


Personally, I have encountered many situation where renderedCallback is a lifesaver.


Try both the code, and leave your thoughts in comment section.

Please subscribe to SFDCBLOGS for more awesome content.

Recent Posts

See All

2 комментария


Loved this example, its literally what i was looking for to understand rendered callback.

Thanks

Лайк

Varun Aggarwal
Varun Aggarwal
06 мар. 2023 г.

Bro, this is seriously a life saver for me.

I started learning LWC from last 1 month and was stuck in lifecycle hooks of LWC.

Everytime I search when to call which method they always says the theory. the DOM and all stuff, no one explained it with a proper example as you did in this post.

I really appreciate your effort that you have put in this. Looking for more such example which explain other lifecycle hooks.

Лайк
bottom of page