Sub topic 1
The life of a component: created, connected, rendered, disconnected
Prerequisites
This chapter assumes you can do the following:
- Read basic JavaScript classes and ES modules.
- Create a Lightning Web Component (LWC) with an HTML template and a JavaScript class.
- Use reactive properties and template expressions.
- Handle basic DOM events.
The working model
An LWC is a JavaScript class that the framework creates, attaches to the page, draws, and later removes. A lifecycle hook is a method on that class. You don't call it. The framework calls it at a fixed point in the component's life.
A component passes through four phases:
- Created. The framework builds the instance and runs
constructor(). - Connected. The framework inserts the component into the DOM and runs
connectedCallback(). - Rendered. The framework calls
render()to pick a template, builds the DOM from it, and runsrenderedCallback(). - Disconnected. The framework removes the component from the DOM and runs
disconnectedCallback().
A fifth hook, errorCallback(), runs only when a descendant component throws an error. It has no fixed place in the sequence.
The loop from Rendered back to Rendering matters most. constructor() and connectedCallback() usually run once for a given insertion. The render step and renderedCallback() can run many times.
What each hook is for
| Hook | Runs when | Typical use |
|---|---|---|
| `constructor()` | The instance is created | Initialize fields. Call `super()` first. |
| `connectedCallback()` | The component is inserted into the DOM | Fetch data, add listeners, read public properties. |
| `render()` | Before each render | Choose between imported templates. |
| `renderedCallback()` | After each render | Work with the rendered DOM. |
| `disconnectedCallback()` | The component is removed from the DOM | Remove listeners, cancel timers. |
| `errorCallback()` | A descendant throws an error | Store the error and show a fallback view. |
Later chapters cover each hook in detail. Here, you only need to know which phase each one belongs to.
A first look at the sequence
The component below logs a message from each hook. Add it to a page and watch the browser console.
import { LightningElement } from 'lwc';
export default class LifecycleLogger extends LightningElement {
message = 'Hello';
constructor() {
super();
console.log('1. constructor');
}
connectedCallback() {
console.log('2. connectedCallback');
}
renderedCallback() {
console.log('3. renderedCallback');
}
disconnectedCallback() {
console.log('4. disconnectedCallback');
}
handleChange(event) {
this.message = event.target.value;
}
}<template>
<lightning-input label="Message" value={message} onchange={handleChange}></lightning-input>
<p>{message}</p>
</template>When the component loads, the console shows 1. constructor, 2. connectedCallback, and 3. renderedCallback, in that order. Each time you type in the input and leave the field, message changes. The template reads message, so the component renders again, and 3. renderedCallback appears once more. The first two lines don't repeat. If you remove the component from the page, 4. disconnectedCallback appears.
Common errors at this stage
- Touching the DOM in the constructor. The component has no children and is not yet attached to the DOM, so
this.template.querySelector()finds nothing. UseconnectedCallback()orrenderedCallback()instead. - Forgetting
super(). A constructor in an LWC class must callsuper()first. Without it, the class throws an error. - Assuming
renderedCallback()runs once. It runs after every render. Code that should run only once needs a guard. - Assuming a removed component is gone for good. The framework can insert the same element again, so
connectedCallback()anddisconnectedCallback()can each run more than once on one instance. Write them so a repeat run is harmless.
Check your understanding
Exercise
A component with a constructor, connectedCallback, and renderedCallback is inserted on a page. A reactive property that the template uses then changes twice, at separate times. In what order do the hooks run, and how many times does each run?
Show answer
constructor runs once, then connectedCallback runs once, then renderedCallback runs after the first render. Each of the two property changes causes a re-render, so renderedCallback runs two more times, for three runs in total. The constructor and connectedCallback do not run again.
Exercise
You need to focus an input element as soon as it exists in the DOM. Which hook can find the element on the first pass, constructor() or renderedCallback(), and why?
Show answer
renderedCallback(). When the constructor runs, the component has no children and is not attached to the DOM, so the input does not exist yet. After the first render, the template's elements exist and a query can find them.