Sub topic 14
Removing from the DOM versus hiding with CSS
This chapter assumes you can write a Lightning Web Component with an HTML template and a JavaScript class. It also assumes you know lwc:if, lwc:elseif, and lwc:else, and that you know the lifecycle hooks connectedCallback and disconnectedCallback. The goal is to decide, for a given piece of UI, whether to remove it from the DOM or keep it and hide it.
Two ways to make content disappear
A user sees the same result either way: something is no longer on screen. The browser and your component see very different results.
- Conditional rendering uses
lwc:if(or a chain withlwc:elseifandlwc:else). When the condition is falsy, the framework does not create the elements. If they existed before, it removes them from the DOM and discards them. - CSS hiding keeps the elements in the DOM and changes how they are displayed. A class that sets
display: none, or thehiddenattribute, are the usual tools.
The difference matters most when the content includes child components, form inputs, or anything with state.
What conditional rendering does
When a branch becomes false, LWC removes its elements from the DOM. For a child component inside that branch, the component is disconnected, and its disconnectedCallback runs. The component instance is discarded.
When the branch becomes true again, LWC creates a new instance. The constructor runs, then connectedCallback, then the component renders. Any state the earlier instance held is gone, because it was a different object.
Three practical consequences follow:
- Child component fields reset to their initial values.
- Hooks fire on every toggle. Use
connectedCallbackto start work such as subscriptions or timers, anddisconnectedCallbackto clean it up. this.template.querySelector()returnsnullfor elements in a branch that is not rendered.
What CSS hiding does
When you hide an element with CSS, the element stays in the DOM. A child component inside it stays connected. No lifecycle hooks fire when you toggle visibility, and the child keeps its state, including the value of a counter, scroll position, and text typed into inputs. Queries still find the element.
The cost is that the hidden content still exists. Its component code runs, it holds memory, and it may keep fetching data or listening for events.
Seeing the difference
The following example places the same child component in two places. One is controlled by lwc:if. The other is wrapped in an element that is hidden with a CSS class. First, the child component. It logs its lifecycle events and keeps a click count.
<!-- counterBox.html -->
<template>
<button onclick={increment}>Clicked {count} times</button>
</template>// counterBox.js
import { LightningElement } from 'lwc';
export default class CounterBox extends LightningElement {
count = 0;
connectedCallback() {
console.log('counterBox connected');
}
disconnectedCallback() {
console.log('counterBox disconnected');
}
increment() {
this.count += 1;
}
}Now the parent. A single button flips both mechanisms at the same time.
<!-- panelSwitcher.html -->
<template>
<button onclick={handleToggle}>Toggle both</button>
<h3>Removed with lwc:if</h3>
<template lwc:if={showRemoved}>
<c-counter-box></c-counter-box>
</template>
<h3>Hidden with CSS</h3>
<div class={hiddenClass}>
<c-counter-box></c-counter-box>
</div>
</template>// panelSwitcher.js
import { LightningElement } from 'lwc';
export default class PanelSwitcher extends LightningElement {
showRemoved = true;
isHidden = false;
get hiddenClass() {
return this.isHidden ? 'is-hidden' : '';
}
handleToggle() {
this.showRemoved = !this.showRemoved;
this.isHidden = !this.isHidden;
}
}/* panelSwitcher.css */
.is-hidden {
display: none;
}Click each counter a few times, then press "Toggle both" twice. The result is:
- The
lwc:ifcounter is back at 0. The console shows one "disconnected" message and then one "connected" message for it. - The CSS-hidden counter keeps its count. The console shows no messages for it after the initial load.
Comparing the two approaches
| Aspect | `lwc:if` (remove) | CSS hiding |
|---|---|---|
| Elements in DOM when off | No | Yes |
| Child component state | Lost, then recreated | Kept |
| `connectedCallback` / `disconnectedCallback` | Fire on each toggle | Do not fire on toggle |
| Cost while off | None | Memory and any running work |
| Cost per toggle | Create and destroy elements | Very low, a style change |
| `querySelector` while off | Returns `null` | Finds the element |
| Initial load | Skips content that is off | Creates all content up front |
Choosing between them
Prefer lwc:if when:
- The content is large, expensive, or rarely shown. Not creating it speeds up the first render.
- You want a clean state each time the content appears, for example a form that should start empty.
- The child starts timers, subscriptions, or network requests that should only run while it is visible. Starting them in
connectedCallbackand stopping them indisconnectedCallbackties their life to the branch. - The content is one of several mutually exclusive states, such as loading, error, and ready.
Prefer CSS hiding when:
- The user toggles the content often, such as a collapsible section, and rebuilding it each time would feel slow.
- State must survive, such as half-typed text in an input or a scroll position.
- The child is costly to initialize, and you would rather pay that cost once.
- You want to animate. A removed element cannot transition, but a class change can animate height or opacity.
If you remove content and still need its state, keep the state in the parent. The parent is not destroyed when the branch toggles, so fields on the parent persist. Pass the values down as public properties and listen for events from the child to update them.
Edge cases and gotchas
Hidden content is still reachable in the DOM. display: none removes an element from the accessibility tree as well as from view, so screen readers skip it. Other hiding techniques, such as moving an element off screen or setting only opacity: 0, do not. Content that is visually hidden this way can still be read aloud and can still receive keyboard focus. For content that should be unavailable, use display: none or the hidden attribute, or remove it with lwc:if.
The hidden attribute can be overridden. The hidden attribute relies on the browser's default style. If your CSS sets display: flex or display: grid on the same element, that rule wins and the element stays visible. A dedicated class that sets display: none avoids that problem.
Hidden inputs still take part in forms. A hidden but still-rendered input keeps its value and validation state. If a required field is hidden with CSS, a validity check in your JavaScript can still fail on it. Removing the field with lwc:if avoids this.
Do not query for removed elements. Code that calls this.template.querySelector('c-counter-box') right after setting a flag to true may get null, because the DOM updates after your handler finishes. Do such queries in renderedCallback, which runs after the template has re-rendered.
Expensive hidden children keep working. A hidden child that polls a server every few seconds keeps polling. If that is not wanted, use lwc:if, or add a public property that tells the child to pause.
Exercise
A product page has a "Details" panel containing a child component with an editable notes field. Users open and close the panel many times and expect their typed notes to remain between toggles. Should you use lwc:if or CSS hiding for the panel, and what is one way to keep the notes if you chose lwc:if anyway?
Show answer
Use CSS hiding. The child component stays connected, so its notes field keeps its value, and toggling is a cheap style change. If you used lwc:if, the child would be destroyed and recreated each time, which resets its fields. To keep the notes in that case, store the notes in a field on the parent (which is not destroyed), pass the value to the child as a public property, and have the child dispatch an event on each change so the parent can update its field.
Exercise
A child component calls setInterval in connectedCallback to refresh data every 5 seconds and clears it in disconnectedCallback. The parent hides the child with a CSS class that sets display: none. What happens to the interval while the child is hidden, and how would you change the parent so the interval stops while the child is not visible?
Show answer
The interval keeps running, because hiding with CSS does not disconnect the child, so neither lifecycle hook fires. To stop it while the child is not visible, wrap the child in lwc:if instead. Removing it from the DOM runs disconnectedCallback, which clears the interval, and re-adding it creates a new instance whose connectedCallback starts a new interval.