Sub topic 4
render(): choosing which template to show
This chapter assumes you can write an LWC with an HTML template and a JavaScript class. It also assumes you know how reactive fields trigger updates and where render() sits among the other hooks. You have already seen constructor() and connectedCallback(). Here you will learn what render() does, when the engine calls it, and what happens to the DOM when it returns a different template.
What render() is for
Every component has a template. Normally the template is the HTML file with the same name as the component. The engine finds it automatically, so you never write any code to select it.
render() lets you override that choice. It is a method on your component class that returns a template. The engine calls it each time it needs to produce the component's DOM. Use it when a component can show two or more structurally different views and the choice depends on the component's state.
render() runs after connectedCallback() and before the template is evaluated and the DOM is built. After the DOM is updated, renderedCallback() runs.
The basic pattern
A template is an HTML file in the component's bundle. When you import an HTML file from JavaScript, the default export is the compiled template function. render() returns one of those imported functions.
Here is the component class:
import { LightningElement } from 'lwc';
import signedInTemplate from './signedIn.html';
import signedOutTemplate from './signedOut.html';
export default class Greeting extends LightningElement {
isSignedIn = false;
render() {
return this.isSignedIn ? signedInTemplate : signedOutTemplate;
}
handleToggle() {
this.isSignedIn = !this.isSignedIn;
}
}The bundle contains two extra HTML files next to greeting.js. Each one must wire up the same handler, because both templates are bound to the same class instance.
<!-- signedIn.html -->
<template>
<p>Welcome back.</p>
<button onclick={handleToggle}>Sign out</button>
</template><!-- signedOut.html -->
<template>
<p>Please sign in.</p>
<button onclick={handleToggle}>Sign in</button>
</template>A component that overrides render() does not need a default greeting.html. If you do keep one, the engine uses it only when render() is absent or returns nothing.
Clicking the button changes isSignedIn. The engine sees that a field read during rendering changed. It schedules a re-render and calls render() again. This time the method returns the other template, and the engine swaps the DOM.
What the engine does with the returned value
The engine compares the template function that render() returns with the one it used last time. Two outcomes are possible.
- Same template as before: the engine runs a normal update. It evaluates the template with the current state and patches only what changed.
- Different template: the engine discards the DOM built from the old template and builds new DOM from the new one.
The second outcome has consequences that surprise people.
- Child components in the old template are removed. Each one gets
disconnectedCallback(), and its state is lost. - Child components in the new template are created from scratch. Each one runs its constructor and
connectedCallback(), even if a child of the same type existed in the old template. - Elements you held a reference to, such as an input found with
this.template.querySelector, are no longer in the DOM. renderedCallback()runs again after the swap, as it does after any render.
Because of this, switching templates is heavier than toggling a conditional block. Do it for real changes of view, not for minor differences.
Rules for writing render()
Treat render() as a function that reads state and returns a template. Keep it free of side effects.
- Return only imported template functions. Do not return strings, HTML fragments, or elements.
- Do not assign to component fields inside
render(). Changing state there can schedule another render, which can loop. - Do not fetch data, query the DOM, or dispatch events in
render(). It runs before the DOM exists for this pass, and it can run many times. - Keep it fast and deterministic. The same state should always produce the same template.
- Return the same imported function for the same state. Creating or choosing a new template on every call forces a full DOM rebuild each time.
What triggers render() to run again
The engine calls render() on the first render and on every later re-render. A re-render is scheduled when a field the component read during its last render changes. The next chapter covers triggers in detail. For render(), the practical point is this: a field you read inside render(), such as isSignedIn above, counts as read during rendering. Changing it schedules a re-render, and the engine then asks render() for the template again.
If render() depends on state, keep that state in a field or a getter that reads fields. State kept in a plain variable outside the class does not trigger a re-render when it changes, so the old template would stay on screen.
Styles belong to templates
When a bundle has several templates, each can have its own stylesheet. A CSS file with the same base name as an HTML file applies to that template. In the example above, signedIn.css styles signedIn.html, and signedOut.css styles signedOut.html.
greeting/
greeting.js
signedIn.html
signedIn.css
signedOut.html
signedOut.cssThe stylesheet named after the component, greeting.css, goes with the default template, greeting.html. If you rely only on alternate templates, do not expect greeting.css to style them.
When you switch templates, the engine also switches the stylesheets. A style that appears in one view does not leak into the other unless you put it in both files.
Interaction with renderedCallback()
renderedCallback() runs after every render, including the one that follows a template swap. A one-time guard flag, like the one in the focus example from earlier in this tutorial, can therefore become wrong in a component that switches templates.
import { LightningElement } from 'lwc';
import formTemplate from './form.html';
import summaryTemplate from './summary.html';
export default class Wizard extends LightningElement {
showSummary = false;
renderedTemplate;
render() {
return this.showSummary ? summaryTemplate : formTemplate;
}
renderedCallback() {
const current = this.showSummary ? 'summary' : 'form';
if (this.renderedTemplate === current) {
return;
}
this.renderedTemplate = current;
const target = this.template.querySelector('[data-autofocus]');
if (target) {
target.focus();
}
}
handleNext() {
this.showSummary = true;
}
handleBack() {
this.showSummary = false;
}
}A single hasRendered boolean would focus the element only in the first template. This version remembers which template it last handled, so it runs the focus logic once per template. Elements marked with data-autofocus get focus when their view appears.
This renderedCallback() only writes to renderedTemplate, which the templates do not read. Writing it does not schedule another render. If a template did read it, the write would trigger a re-render, and the guard would be the only thing stopping a loop.
render() or lwc:if?
Both tools choose what appears on screen. They fit different sizes of change.
| Situation | Better choice | Reason |
|---|---|---|
| One section appears or disappears | `lwc:if` in a single template | Only that block is added or removed. The rest of the DOM is kept. |
| Two or three small variations in one layout | `lwc:if` and `lwc:else` | One file keeps the whole layout visible to readers. |
| Two entirely different layouts, such as a form and a read-only summary | `render()` with separate templates | Each template stays simple, with no large conditional wrappers. |
| Different markup per state, with different styles | `render()` | Each template has its own stylesheet. |
| Child component state must survive the change | `lwc:if` or CSS-based hiding | A template swap destroys and recreates children. |
A useful test is to ask whether the two views share most of their markup. If they do, use a conditional. If they share almost nothing, use render().
Common problems
- The component shows the wrong view and never updates. The state that
render()reads is not a field or a getter over fields, so no re-render is scheduled. - Child components lose their input or reset after a toggle. The swap destroys and recreates them. Move that state to the parent, or use a conditional instead of a template swap.
- An element reference becomes null. A reference taken in
renderedCallback()points into the old template after a swap. Query the DOM again after each render rather than caching the element. - An infinite loop.
render()orrenderedCallback()writes a field that a template reads. Remove the write or guard it. render()returns something that is not a template. The engine reports an error. Always return an imported template function.- A handler is missing in one template. Both templates run against the same class. A template that references
{handleToggle}fails to wire it up if the class has no such method, so check that every handler named in any template exists.
Testing the choice
In Jest, you can test which template is shown by rendering the component and checking the DOM, then changing state and checking again.
import { createElement } from 'lwc';
import Greeting from 'c/greeting';
describe('c-greeting', () => {
afterEach(() => {
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
});
it('swaps templates when the button is clicked', async () => {
const element = createElement('c-greeting', { is: Greeting });
document.body.appendChild(element);
expect(element.shadowRoot.querySelector('p').textContent).toBe('Please sign in.');
element.shadowRoot.querySelector('button').click();
await Promise.resolve();
expect(element.shadowRoot.querySelector('p').textContent).toBe('Welcome back.');
});
});The await Promise.resolve() waits for the engine to finish its re-render. Without it, the assertion runs before the new template exists.
Summary
render()returns an imported template function. It runs afterconnectedCallback()and again on every re-render.- Same template: the engine patches the DOM. A different template: the engine rebuilds the DOM and recreates child components.
- Keep
render()free of side effects, and drive it from reactive state. - Stylesheets pair with templates by file name.
- A guard in
renderedCallback()needs to account for template swaps. - Use
render()for different layouts andlwc:iffor small differences.
Exercise
A component imports editTemplate and viewTemplate. Its render() returns this.isEditing ? editTemplate : viewTemplate. A child c-comment-box appears in both templates. A user types text into the child, then clicks a button that sets isEditing to false. The text disappears. Why does this happen, and how would you keep the text?
Show answer
Returning a different template makes the engine discard the old DOM and build new DOM. The c-comment-box in the old template is disconnected and destroyed, and the one in the new template is a new instance with empty state. To keep the text, either store it in the parent, pass it down through a public property, and let the parent update it from the child's change event, or replace the template swap with lwc:if and lwc:else blocks inside one template, which keeps a child that sits outside the conditional.