A lifecycle method runs automatically at a defined point in a web component’s lifetime. Use one when work must happen on connection, before rendering, after rendering, or on disconnection. Web components provide standard callbacks; libraries such as Lit, Stencil, and fast-element add their own hooks. section 5.4 section 6.5 section 7.1
Calculate an area before rendering
An area-calculator component has height and width properties and displays their product. In Lit, willUpdate(changedProps) can check whether either property changed, then set area to height * width before the next render. The rendered value is ready without putting that calculation in a DOM handler. section 5.4
Listing 5.13 area-calculator.ts willUpdate lifecycle method
willUpdate(changedProps: Map<string, unknown>) {
if (changedProps.has("height") || changedProps.has("width")) {
this.area = this.height * this.width;
}
}
The short willUpdate listing shows the property-change check and derived area value. section 5.4
Choose a hook by when the work must happen:
- In Lit, shouldUpdate can skip an unnecessary render; willUpdate prepares values; updated can find newly rendered elements, such as a form control that needs focus. section 5.4
- In Stencil, componentWillLoad runs before the first render, while componentDidLoad runs after it. Connection and disconnection callbacks run each time the component enters or leaves the DOM. section 6.5
- In fast-element, a property-nameChanged method receives the old and new values of that property. section 7.1
Keep DOM work aligned with the rendering system. Lit’s updated hook can act on newly rendered elements; overriding its lower-level update method is rare and requires calling super.update(changedProps). In Stencil, manipulating DOM nodes from component methods can conflict with its virtual DOM. section 5.4 section 6.5



