Sub topic 13
What happens to child components when a branch toggles
This chapter assumes you can write a parent and child Lightning Web Component, pass values through @api properties, and use lwc:if and lwc:else in a template. It covers what the framework does to child components when a branch turns on or off, and how to write code that handles it.
A branch is created and destroyed, not hidden
When the condition on an lwc:if branch becomes falsy, LWC removes that branch's elements from the DOM. Every child component inside the branch is disconnected and then discarded. When the condition becomes truthy again, LWC builds the branch from scratch. That builds new child component instances. It does not bring back the old ones.
This has three consequences:
- Child state does not survive. Fields, cached values, and anything set after construction are gone.
- Lifecycle hooks run again. A child gets a new
constructor,connectedCallback, andrenderedCallbackeach time the branch appears. - Cleanup is your job. The framework calls
disconnectedCallbackas the child leaves, and anything the child started must be stopped there.
The parent is unaffected. Its fields keep their values while a branch comes and goes, so the parent is where state that must outlive the toggle belongs.
The lifecycle sequence
The following table shows what each toggle does to a child inside the branch.
| Toggle | What happens to the child | Hooks that run |
|---|---|---|
| Condition becomes truthy | A new instance is created, inserted, and rendered | `constructor`, `connectedCallback`, then `renderedCallback` |
| Condition stays truthy, parent re-renders | The same instance stays. Changed `@api` values are pushed in | `renderedCallback` only if the child re-renders |
| Condition becomes falsy | The instance is removed from the DOM and discarded | `disconnectedCallback` |
| Condition becomes truthy again | A different, new instance is created | The full creation sequence again |
Two details matter in practice:
renderedCallbackruns after every render of the child, not only the first. A child that updates a reactive field once per second runs it once per second. Guard one-time setup with a flag, or put it inconnectedCallback.- Hooks follow the usual parent and child order. The child's
connectedCallbackruns when the child is inserted. The parent'srenderedCallbackruns after the children have rendered.
Worked example: a ticker that starts over
The child below starts an interval timer when it connects. It stops the timer when it disconnects.
import { LightningElement, api } from 'lwc';
export default class Ticker extends LightningElement {
@api label;
seconds = 0;
intervalId;
constructor() {
super();
console.log('ticker: constructor');
}
connectedCallback() {
console.log('ticker: connected');
this.intervalId = setInterval(() => {
this.seconds += 1;
}, 1000);
}
disconnectedCallback() {
console.log('ticker: disconnected');
clearInterval(this.intervalId);
}
}<template>
<p>{label}: {seconds} s</p>
</template>The parent renders the child in one branch and a message in the other:
<template>
<button onclick={handleToggle}>{buttonLabel}</button>
<template lwc:if={showTicker}>
<c-ticker label="Session"></c-ticker>
</template>
<template lwc:else>
<p>Ticker is off.</p>
</template>
</template>import { LightningElement } from 'lwc';
export default class TickerHost extends LightningElement {
showTicker = true;
get buttonLabel() {
return this.showTicker ? 'Turn off' : 'Turn on';
}
handleToggle() {
this.showTicker = !this.showTicker;
}
}Let the ticker reach 5 seconds, then click the button twice. The console shows the following:
ticker: constructorticker: connectedticker: disconnectedafter the first clickticker: constructorandticker: connectedafter the second click
The display restarts at 0 because the second ticker is a new instance with a fresh seconds field.
If you remove the clearInterval call, the old timer keeps running after the child is gone. Its callback still holds a reference to the discarded instance, so that instance is never garbage collected. Each toggle adds another running timer.
Keeping state across toggles
If a value must survive the branch turning off, store it in the parent and pass it down. The child then starts from that value each time.
import { LightningElement, api } from 'lwc';
export default class Counter extends LightningElement {
@api value = 0;
handleClick() {
this.dispatchEvent(
new CustomEvent('change', { detail: this.value + 1 })
);
}
}<template>
<button onclick={handleClick}>Clicked {value} times</button>
</template>The parent keeps the count and updates it from the event:
<template>
<button onclick={handleToggle}>Toggle counter</button>
<template lwc:if={showCounter}>
<c-counter value={count} onchange={handleChange}></c-counter>
</template>
</template>import { LightningElement } from 'lwc';
export default class CounterHost extends LightningElement {
showCounter = true;
count = 0;
handleToggle() {
this.showCounter = !this.showCounter;
}
handleChange(event) {
this.count = event.detail;
}
}The Counter component never changes its own value. It reports the new number, and the parent owns it. When the branch comes back, the new Counter receives the current count and shows it. This follows the general LWC data flow: values go down through properties, and events go up.
The same child in two branches is two instances
Putting the same tag in both branches of a chain does not share an instance between them.
<template>
<template lwc:if={isCompact}>
<c-ticker label="Compact"></c-ticker>
</template>
<template lwc:else>
<c-ticker label="Full"></c-ticker>
</template>
</template>When isCompact changes, the first ticker is disconnected and a second one is constructed. The two do not share state, and the timer restarts. If you only want to change how a single child looks, keep one child outside the chain and pass it a property instead. The chain can then control the surrounding markup.
<template>
<c-ticker label="Session" compact={isCompact}></c-ticker>
</template>Here the same instance stays alive, and compact is updated on it as an ordinary @api change.
Removing versus hiding
Conditional rendering removes the elements, while CSS hiding only changes how they look. Hidden children stay connected and keep their state and timers. The cost is that they are created at startup, even if the user never sees them.
| Concern | `lwc:if` | CSS hiding |
|---|---|---|
| Child state kept while off | No | Yes |
| Child runs hooks and timers while off | No | Yes |
| Cost of showing it again | Full creation | Class change |
| Cost of first load | None for a branch that never shows | Child is built immediately |
Use lwc:if when the child is expensive, such as one that makes server calls on connect, or when it should start fresh each time. Use CSS hiding when the child holds state the user would be upset to lose, such as a half-filled form in a tab that is switched away from and back. If you use CSS hiding, remember that the child's connectedCallback already ran, so the child must not start work that should only happen when it is visible.
Common mistakes
- Starting work in
connectedCallbackand never stopping it. This leaves timers and listeners alive after the child is gone. - Expecting a child's fields to still hold values after the branch turns off. They do not. Keep the value in the parent.
- Expecting a one-time
connectedCallbackper page load. A child inside a branch connects once per time the branch appears. - Reading child elements with
this.template.querySelectorright after toggling a condition. The DOM updates when the component re-renders, so the new child is not available untilrenderedCallbackruns. - Putting one-time setup in
renderedCallbackwithout a guard. It runs after every render.
Exercise
A parent shows <c-form-draft> inside <template lwc:if={isEditing}>. The child keeps the user's typed text in a field. A user types a few words, clicks "Cancel" (which sets isEditing to false), then clicks "Edit" again, and the text is gone. Explain why, and give two ways to keep the text.
Show answer
When isEditing becomes false, the branch is removed and the child instance is disconnected and discarded, along with its fields. Clicking "Edit" builds a new instance whose fields start empty. To keep the text, either store the draft in a parent field and pass it down through an @api property, updating it from a change event raised by the child, or render the child always and hide it with CSS so the same instance stays alive.