Sub topic 7
Hook order across parent and child components
This chapter assumes you can write a single LWC with a JavaScript class and an HTML template. It also assumes you know what constructor(), connectedCallback(), renderedCallback() and disconnectedCallback() do for one component. Here the question changes from "when does my hook run?" to "when does it run relative to the hooks of the components around it?"
Why order across components matters
Real components are rarely alone. A parent template contains child components, and each child may contain more. Every one of them has its own hooks, and the engine runs them in a fixed sequence. If you assume the wrong sequence, you get bugs such as these:
- A parent calls
this.template.querySelector('c-child')inconnectedCallback()and getsnull. - A child reads a value from its parent in its constructor and gets
undefined. - A parent tries to measure its content in
renderedCallback()and finds the children not yet rendered, because the author expected the opposite order.
The rule behind all of these is that creation and connection move down the tree, from parent to child. Rendering completes up the tree, from child to parent.
The creation phase: top down
When a parent is inserted into the DOM, its hooks run in this order:
- The parent's
constructor()runs. - The parent's
connectedCallback()runs. - The parent's
render()runs, and the engine evaluates its template. - For each child found in the template, the child goes through its own constructor,
connectedCallback()andrender(). - Each child's
renderedCallback()runs once the child's own template is on the page. - The parent's
renderedCallback()runs last, after all its children have rendered.
The parent's connectedCallback() runs before the parent's template is evaluated. At that point the children do not exist yet, so the parent has nothing to query. The parent's renderedCallback() runs after the children are built, so the children are there by then.
Seeing the order with logging
The most reliable way to learn the order is to log it. Create a child component named logChild:
<!-- logChild.html -->
<template>
<p>Child {label}</p>
</template>// logChild.js
import { LightningElement, api } from 'lwc';
export default class LogChild extends LightningElement {
@api label;
constructor() {
super();
console.log(`child ${this.label} constructor`);
}
connectedCallback() {
console.log(`child ${this.label} connectedCallback`);
}
renderedCallback() {
console.log(`child ${this.label} renderedCallback`);
}
disconnectedCallback() {
console.log(`child ${this.label} disconnectedCallback`);
}
}Next, create a parent named logParent that contains two children and a button to remove them:
<!-- logParent.html -->
<template>
<template lwc:if={showChildren}>
<c-log-child label="A"></c-log-child>
<c-log-child label="B"></c-log-child>
</template>
<button onclick={hide}>Remove children</button>
</template>// logParent.js
import { LightningElement } from 'lwc';
export default class LogParent extends LightningElement {
showChildren = true;
constructor() {
super();
console.log('parent constructor');
}
connectedCallback() {
console.log('parent connectedCallback');
}
renderedCallback() {
console.log('parent renderedCallback');
}
disconnectedCallback() {
console.log('parent disconnectedCallback');
}
hide() {
this.showChildren = false;
}
}When you add c-log-parent to a page, the console shows output like this:
parent constructor
parent connectedCallback
child undefined constructor
child A connectedCallback
child A renderedCallback
child undefined constructor
child B connectedCallback
child B renderedCallback
parent renderedCallbackTwo details in this output matter.
First, the child's constructor logs undefined for the label. The parent sets public properties after the constructor finishes. By the time connectedCallback() runs, label holds its value. This is why initialization that depends on @api values belongs in connectedCallback(), not in the constructor.
Second, parent renderedCallback appears last, after both children have rendered.
The diagram shows the same sequence for a parent with one child.
What is guaranteed and what is not
You can rely on these rules:
- A parent's
connectedCallback()runs before any child'sconstructor(). - Every child's
renderedCallback()runs before the parent'srenderedCallback(). - Public properties passed by the parent are set before the child's
connectedCallback().
Do not rely on how the hooks of sibling children interleave. In the output above, child A finishes completely before child B starts. That is how the current engine behaves, but the platform does not promise it. If siblings must coordinate, have them communicate with events through their parent. Do not depend on one sibling having rendered before the other.
Re-rendering: only affected components run again
After the first render, hooks do not all run again together. A re-render happens for a component when a reactive value that its template uses changes. For the parent, this means the parent's render() and renderedCallback() run again. A child re-renders only in these cases:
- A reactive value that the child's own template reads changed.
- A public property that the parent passes to the child changed.
If the parent re-renders because of an unrelated field, the child's renderedCallback() does not run. Likewise, the child's constructor and connectedCallback() do not run again, because the child instance already exists and stays connected.
This changes how you read logs. If you click a button that changes a parent field the child does not use, you see only this:
parent renderedCallbackIf the change flows into a child through a public property, the order is again child first, then parent:
child A renderedCallback
parent renderedCallbackThe child renders first and the parent finishes afterward, so the bottom-up rule from the creation phase also applies to updates.
Conditional children are created and destroyed
Children inside lwc:if, lwc:elseif, lwc:else, or an iteration are created only when the template needs them. That has two consequences:
- A child that is initially hidden does not run any hooks until the condition becomes true. Then it goes through its full constructor,
connectedCallback()and render sequence. - A child whose condition becomes false is removed from the DOM and runs
disconnectedCallback(). If the condition becomes true again, the engine creates a new instance, and its constructor andconnectedCallback()run again. State stored in fields of the old instance is gone.
Because of the second point, connectedCallback() may run many times over the life of a parent. Initialization that must happen once per child instance is correct there. Initialization that must happen once per page is not.
The removal phase
When the parent is removed, for example by clicking the button in logParent, the order reverses direction for the disconnect. The parent's disconnectedCallback() runs first, then the disconnectedCallback() of each child in its subtree.
If you remove only the children with lwc:if, the console shows:
child A disconnectedCallback
child B disconnectedCallback
parent renderedCallbackThe parent re-renders because showChildren changed. The children are disconnected as part of that re-render, and then the parent's renderedCallback() runs.
Do not write cleanup code that assumes a particular order between a parent and its children. Each component should release only the resources it created itself. A child should not rely on the parent still being intact when its own disconnectedCallback() runs.
Practical rules from the order
| Task | Where it works | Why |
|---|---|---|
| Read `@api` values passed by the parent | `connectedCallback()` of the child | The values are set before this hook, but not before the constructor. |
| Query the component's own template | `renderedCallback()` | The template exists only after the first render. |
| Query child components that the parent owns | Parent's `renderedCallback()` | Children render before the parent's `renderedCallback()`. |
| Query parent state from a child | Do not do it. Use `@api` properties or events. | Children should not depend on a parent's internals. |
| Start work that must exist before children appear | Parent's `connectedCallback()` | It runs before any child is created. |
Passing data down safely
Because the parent's connectedCallback() runs before the children exist, it is a good place to prepare data that children will receive:
import { LightningElement } from 'lwc';
export default class OrderPage extends LightningElement {
orderLines = [];
connectedCallback() {
this.orderLines = [
{ id: 1, name: 'Widget' },
{ id: 2, name: 'Gadget' }
];
}
}<template>
<template for:each={orderLines} for:item="line">
<c-order-line key={line.id} line={line}></c-order-line>
</template>
</template>Each c-order-line receives its line value before its own connectedCallback() runs. The child can use this.line there without checking for undefined.
The same code written with an asynchronous call changes the picture. If the parent fetched the lines in connectedCallback() with a promise, the first render would run with an empty list, and the children would appear later when the data arrives. In that case the children are created later, and their hooks run later. Your template should handle the empty state.
Errors cross the parent and child boundary
The tree structure also governs where errors travel. If a child's hook throws, the engine looks for an errorCallback(error, stack) on an ancestor. The nearest ancestor that defines one receives the error, so a parent can act as a boundary around its subtree. A component's own errorCallback() does not catch errors thrown by that component itself. It catches errors from its descendants. The next chapters cover this hook in detail.
Common mistakes with ordering
- Querying children in
connectedCallback(). The result isnullor an empty list because the template has not been evaluated. Move the query torenderedCallback(). - Reading
@apivalues in the constructor. They are not set yet. UseconnectedCallback(). - Expecting the parent's
renderedCallback()before the child's. It always comes after. - Assuming a child's
connectedCallback()runs once. A conditionally rendered child gets a new instance each time its condition becomes true. - Relying on sibling order. It is not part of the contract.
Exercise
A parent template contains a conditional child with lwc:if={showChild}. The parent starts with showChild = false. The user clicks a button that sets showChild to true, clicks again to set it to false, then clicks a third time to set it to true. How many times does the child's constructor run, and in the console, where does the parent's renderedCallback appear relative to the child's renderedCallback on the third click?
Show answer
The constructor runs twice: once on the first click that sets showChild to true, and once on the third click. The false click removes the first instance, and the third click creates a new one. On each of those clicks, the child's renderedCallback runs first and the parent's renderedCallback runs after it, because children finish rendering before their parent.
Exercise
A developer writes this.template.querySelector('c-chart') in a parent's connectedCallback() and always gets null. Why, and where should the code go?
Show answer
In connectedCallback() the parent's template has not been evaluated yet, so the c-chart child does not exist. The query should move to the parent's renderedCallback(), which runs after all children have rendered. Because renderedCallback() runs after every render, guard the code with a flag or check that the element exists so it does not repeat unnecessary work.