Explain the LWC lifecycle hooks and the order in which they fire for a parent and child component.
Answer
Hooks: constructor(), connectedCallback(), render(), renderedCallback(), disconnectedCallback(), errorCallback(error, stack).
Order when a parent contains a child:
- Parent
constructor - Parent
connectedCallback - Parent
render - Child
constructor - Child
connectedCallback - Child
render - Child
renderedCallback - Parent
renderedCallback
Notes:
- Call
super()first in the constructor; don't access attributes or children there. connectedCallbackfires when inserted into the DOM; use it to fetch data or subscribe.renderedCallbackfires after every render, so guard one-time logic with a flag.disconnectedCallbackis for cleanup (unsubscribe, remove listeners).errorCallbackcatches errors from child components in the lifecycle.
lwclifecycle