Reactive properties in Lit
Learn Lit reactive properties with live examples: @property and @state, attribute names, converters, reflect, useDefault, hasChanged, and decorators.
- 01Declare properties and stateWrite
static properties,@property(), and@state(), and know that state never gets an attribute. - 02Control the attributeChoose the attribute's name, a
typeor aconverter,reflect, anduseDefault, and know when Lit writes the attribute. - 03Avoid the update trapsKnow why
push(), class fields, and standard decorators withoutaccessorstop updates, and whathasChangedandnoAccessorchange.
What are reactive properties in Lit?
Asha wants a rating on every tea at Leaf and Kettle. Visitors give each tea one to five cups. She writes the rating with Lit, as <tea-cup-rating value="3" max="5">. Ravi reads her code and frowns. "There's no getter, no setter, and no attribute callback. Where do the properties come from?"
What does Lit build from a few lines of options? And when does it touch the attribute?
A reactive property in Lit is a property that draws the component again when it changes. You declare it in static properties, or with @property() in TypeScript. Lit writes its getter and setter, watches an attribute for it, and can copy the property back to that attribute.
Here is Asha's first rating:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3" max="5"></tea-cup-rating><button id="more">One more cup</button><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); document.querySelector("#more").addEventListener("click", async () => { rating.value += 1; await rating.updateComplete; console.log(`value attribute: ${rating.getAttribute("value")}`); });</script>- Lines 1 to 3 are the import map from lesson 20.1. The name
litmeans Lit 3.3.3, from esm.sh. - Line 4 is the rating, with two attributes. Line 5 is a button.
- Line 10 adds a cup on each press. Line 11 waits for Lit's update. Line 12 prints the attribute.
The tea-cup-rating.js tab holds the component:
import { LitElement, html } from "lit";
export class TeaCupRating extends LitElement {
static properties = {
value: { type: Number, reflect: true },
max: { type: Number },
};
constructor() {
super();
this.value = 0;
this.max = 5;
}
render() {
const cups = Array.from({ length: this.max }, (_, index) => (index < this.value ? "●" : "○"));
return html`${cups.join("")}`;
}
}
customElements.define("tea-cup-rating", TeaCupRating);- Lines 4 to 7 declare two properties. Each key is a property's name, and its object holds the options.
- Line 5:
valueis a number, and it reflects. To reflect means Lit copies the property back into its attribute. - Line 6:
maxis a number too. It doesn't reflect. - Lines 9 to 13 set the starting values: no cups, out of five.
- Line 16 makes a full cup for each one below value, and an empty cup for the rest. Line 17 draws them.
The rating shows ●●●○○. Press One more cup. It shows ●●●●○, and the console prints value attribute: 4.
Line 10 only set a property. Lit did the rest: it drew the cups again, and it wrote 4 into the attribute. Your own kit did those jobs by hand. ReactiveTea drew on a change (lesson 18.1), and TeaElement made the getters and setters (lesson 19.2). Lit's docs list the same jobs: a getter and setter for each property, a watched attribute, and an update when it changes (Lit).
At the counter, each teapot has a label. When a new label goes on, Ravi brews what it says. The tea inside is what customers drink. Some pots also get their label rewritten whenever the tea changes, so anyone can read it from the outside.
- In real life: The tea inside the pot
- In JavaScript: The property, value
- In real life: The label on the outside
- In JavaScript: The attribute, value="3"
- In real life: Pouring what the label says
- In JavaScript: Lit reading the attribute on every change
- In real life: Rewriting the label after the tea changes
- In JavaScript: reflect: true
A reactive property is a setter that Lit writes for you. Set it, and the component draws again. Its attribute is a label: Lit reads it on every change, and rewrites it only when the property reflects.
What is the difference between @property and @state in Lit?
Asha wants one more thing. When the pointer moves over the cups, they should fill in, to preview the rating. That preview isn't something a page sets. It belongs to the rating alone.
Lit has two kinds of reactive property for this (Lit):
- A public property is part of the component's API. The page sets it, from HTML or JavaScript. Lit's docs say to treat it as input.
- Internal state is a reactive property that only the component sets. It has no attribute.
In TypeScript, the decorator says which is which:
@property({ type: Number, reflect: true }) value = 0;
@property({ type: Number }) max = 5;
@state() private hovered = 0;Lines 1 and 2 are public properties. Line 3 is state. @state() is @property() with state: true and attribute: false (state.ts, lines 41 to 50). In JavaScript, you write state: true in static properties. Here is the rating, grown:
import { LitElement, html, css } from "lit";
export class TeaCupRating extends LitElement {
static properties = {
value: { type: Number, reflect: true },
max: { type: Number },
hovered: { state: true },
};
static styles = css`button { border: 0; padding: 0; background: none; font-size: 24px; }`;
constructor() {
super();
this.value = 0;
this.max = 5;
this.hovered = 0;
}
pick(cup) {
this.value = cup;
this.dispatchEvent(new Event("change"));
}
render() {
const shown = this.hovered || this.value;
const cups = Array.from({ length: this.max }, (_, index) => index + 1);
return cups.map(
(cup) => html`<button
aria-label="${cup} of ${this.max} cups"
@pointerenter=${() => (this.hovered = cup)}
@pointerleave=${() => (this.hovered = 0)}
@click=${() => this.pick(cup)}
>${cup <= shown ? "●" : "○"}</button>`,
);
}
}
customElements.define("tea-cup-rating", TeaCupRating);- Line 7 declares
hoveredas state: the cup under the pointer. - Lines 11 to 16 set the starting values.
hoveredis 0: no cup is under the pointer. - Lines 18 to 21: a click sets
valueand sends achangeevent. A component may change its own public property when the user acts, and then it should send an event (Lit). Events came in lesson 5.3. - Line 24 picks what to show: the cup under the pointer, or the value when there's none.
- Lines 25 to 33 make one button for each cup. Lit draws an array of templates in order, like the lists of lesson 18.3.
- Lines 29 to 31 add listeners. The
@names work as they did in html.js (lesson 18.2). The next lesson covers Lit's bindings in full.
Now ask the rating which attributes it watches:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3"></tea-cup-rating><script type="module"> import { TeaCupRating } from "./tea-cup-rating.js"; console.log(`Watched attributes: ${TeaCupRating.observedAttributes.join(", ")}`); const rating = document.querySelector("tea-cup-rating"); rating.setAttribute("hovered", "5"); await rating.updateComplete; console.log(`hovered: ${rating.hovered}`);</script>- Line 7 prints
observedAttributes, the browser's list of attributes to watch (lesson 3.4). Lit builds it from static properties. - Line 9 sets a
hoveredattribute anyway. Line 11 prints the property after the update.
It prints Watched attributes: value, max and hovered: 0. The attribute did nothing. Now point at the fifth cup: all five fill in, ●●●●●. Move away: ●●●○○ again. Click the fourth cup, and it keeps ●●●●○.
value and max each watch an attribute, so HTML can set them. hovered has none: only the rating's own pointer code sets it.Lit leaves state out of the list on purpose. createProperty() turns state: true into attribute: false (reactive-element.ts, lines 702 to 705). So no HTML can set it by mistake, and the rating's API stays small.
A customer hands in an order slip: one oolong, large. The cook also keeps a notepad: which pan is hot, what to stir next. The cook acts on both. But no customer writes on the notepad.
- In real life: The order slip a customer hands in
- In JavaScript: A public property, like value
- In real life: Writing the order on paper at the counter
- In JavaScript: Setting the attribute in HTML
- In real life: The cook's notes on which pan is hot
- In JavaScript: State, like hovered
- In real life: Notes no customer ever writes on
- In JavaScript: No attribute for state
Is state private, then? No. Line 11 read rating.hovered from outside. Lit's docs only say outside code shouldn't use it. They suggest private in TypeScript, and a leading underscore in JavaScript, like _hovered. The only option state takes is hasChanged (Lit).
How does Lit turn attributes into properties?
Each public property watches one attribute. Two options decide which attribute, and how to read its text.
Which attribute does a property watch?
By default, the property's name in lowercase. The attribute option can give another name, or false for none (Lit). This page declares one of each:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><script type="module"> import { LitElement } from "lit"; class TeaTin extends LitElement { static properties = { teaName: {}, blendName: { attribute: "blend-name" }, notes: { attribute: false }, }; } customElements.define("tea-tin", TeaTin); console.log(TeaTin.observedAttributes.join(", "));</script>- Line 9:
teaName, with no options. - Line 10:
blendName, watching an attribute namedblend-name. - Line 11:
notes, with no attribute. It's for an array, which the page sets from JavaScript.
It prints teaname, blend-name. HTML stores attribute names in lowercase, so the browser's list must be lowercase too (lesson 3.4). So Lit lowercases the name. Your TeaElement added dashes instead (lesson 19.2). For a dashed name in Lit, give it with attribute.
What does the type option do?
Attributes are always text (lesson 5.1). The type option tells Lit's default converter how to read that text: String, which is the default, Number, Boolean, Object, or Array. For a Number, it calls Number() (reactive-element.ts, lines 375 to 377). Watch what that means:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="lots"></tea-cup-rating><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; console.log(rating.value); rating.value = "4"; console.log(typeof rating.value);</script>- Line 4 gives the rating text that isn't a number.
- Line 9 prints the property after the first update.
- Line 10 sets the property to the string
"4". Line 11 prints its type.
It prints NaN, then string. The rating still shows ●●●●○, because line 32 of the tab compares cup <= shown, and JavaScript turns "4" into a number there.
So type is a hint for reading attributes, not a check. Lit's docs say not to confuse it with type checking (Lit). A value set from JavaScript is stored as it is. Why it matters: if your code needs a number, pass a number, or let TypeScript check it.
One more rule from Lit's docs: a Boolean property must start as false. Any Boolean attribute that's there means true, so HTML could never turn off one that starts true (Lit). Lesson 5.2 showed the same with disabled="false".
When does Lit reflect a property to its attribute?
With reflect: true, Lit writes the property into its attribute. But not at once:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3"></tea-cup-rating><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; rating.value = 4; console.log(`Right after: ${rating.getAttribute("value")}`); await rating.updateComplete; console.log(`After the update: ${rating.getAttribute("value")}`);</script>- Line 8 waits for the first update. Line 9 sets the value.
- Line 10 reads the attribute at once. Line 12 reads it again, after the update.
It prints Right after: 3, then After the update: 4.
Lit writes reflected attributes in update(), for each property that changed (reactive-element.ts, lines 1655 to 1662). That's a microtask after the set, with the drawing. TeaElement wrote them inside the setter (lesson 19.2). The loop guard you built there is in Lit too: while Lit writes the attribute, it ignores that attribute's callback (lines 1213 to 1228).
What does useDefault do?
There's a catch. The starting value from the constructor counts as a change, so the first update reflects it. A rating with no value attribute grows one: value="0". The page never wrote that.
The useDefault option fixes it. Lit 3.3.0 added it (Lit's changelog). It does two things (Lit):
- The starting value doesn't reflect.
- Removing the attribute sets the property back to the starting value.
The page is the same in both choices. Only line 5 of the tea-cup-rating.js tab changes:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating></tea-cup-rating><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; console.log(`At the start: ${rating.getAttribute("value")}`); rating.setAttribute("value", "4"); await rating.updateComplete; rating.removeAttribute("value"); await rating.updateComplete; console.log(`After removing it: ${rating.value}`);</script>It prints At the start: 0 and After removing it: null. The first update wrote the starting 0 into the page, and removing the attribute left the property at null.
- Line 4 has no value attribute. Line 9 prints the attribute after the first update.
- Lines 10 to 13 give the rating an attribute, then take it away. Line 14 prints the property.
- Without useDefault:
At the start: 0andAfter removing it: null. - With useDefault:
At the start: nullandAfter removing it: 0.
Without useDefault, the Number converter reads a missing attribute as null. With it, Lit falls back to the default it kept (lines 1251 to 1255). The same first update explains the type page: value="lots" became value="NaN", because Lit wrote back what value held. Later changes still reflect, even back to the default: setting 0 writes value="0".
Every tin on the shelf has a regular price in the till. Nobody puts a sticker on a tin just to repeat it. When Ravi marks a tin down, a sticker goes on. Peel it off, and the till charges the regular price again.
- In real life: The regular price, kept in the till
- In JavaScript: The default from the constructor, 0
- In real life: A special price sticker
- In JavaScript: The value attribute
- In real life: No sticker until someone sets a special price
- In JavaScript: useDefault: true
- In real life: Peeling off the sticker brings back the regular price
- In JavaScript: Removing the attribute restores 0
Lit's docs add three tips (Lit):
- Reflect sparingly. Attributes are input from the page. For a component's own state, use custom states (lesson 12.3).
- Give reflecting properties
useDefault: true. - Don't reflect objects or arrays. They turn into big strings in the page.
Lesson 5.1 asked which properties to reflect. The answer still holds in Lit.
How do you write a custom attribute converter in Lit?
Asha's old menu pages write ratings as 4/5. Number() reads that as NaN. A converter is an object with two functions. It takes the place of Lit's default converter (Lit):
fromAttribute(text)turns the attribute's text into the property's value. The text isnullwhen the attribute is gone.toAttribute(value)turns the value into text, for a property that reflects. Returningnullorundefinedremoves the attribute.
const cupsConverter = {
fromAttribute(text) {
return text === null ? null : Number(text.split("/")[0]);
},
toAttribute(value) {
return value > 0 ? String(value) : null;
},
};- Line 3: no attribute gives
null. Any other text is split at the slash, and the part before it becomes a number."4/5"gives 4, and so does"4". - Line 6: a rating above 0 becomes text. 0 becomes
null, so an unrated tea has no value attribute.
The tab puts it on value, with value: { converter: cupsConverter, reflect: true, useDefault: true }.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="4/5"></tea-cup-rating><button id="clear">Clear</button><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; console.log(`value: ${rating.value}, attribute: ${rating.getAttribute("value")}`); document.querySelector("#clear").addEventListener("click", async () => { rating.value = 0; await rating.updateComplete; console.log(`Has a value attribute: ${rating.hasAttribute("value")}`); });</script>- Line 4 writes the rating the old way.
- Line 10 prints the property and the attribute after the first update.
- Lines 11 to 15: Clear sets the value to 0, then checks for the attribute.
It prints value: 4, attribute: 4/5, and shows ●●●●○. Press Clear. It prints Has a value attribute: false, and shows ○○○○○.
useDefault matters here too. Without it, the first update would rewrite 4/5 as 4. With it, the page keeps what it wrote.
A converter can also be one function. Lit uses it as fromAttribute (lines 1242 to 1247). For reflecting, Lit then writes the value with its default converter, which turns 0 into "0", not null:
value: { converter: (text) => (text === null ? null : Number(text.split("/")[0])), reflect: true, useDefault: true },Line 1 reads the text the same way. There's no toAttribute, so a 0 now stays on the page as value="0".
Regulars write their orders by hand, each in their own way. The barista knows how to read each one, and types the right number into the till. When the kitchen needs a slip, the barista writes it the shop's way.
- In real life: A customer writes "4/5 cups" on the slip
- In JavaScript: value="4/5"
- In real life: The barista reads it as 4
- In JavaScript: fromAttribute()
- In real life: Copying the order onto a slip for the kitchen
- In JavaScript: toAttribute()
- In real life: No slip at all for no tea
- In JavaScript: Returning null removes the attribute
Your kit did all of this in lesson 19.2, with different choices. Read each row across: what you declare, what TeaElement does, and what Lit does.
| What you declare | TeaElement, from lesson 19.2 | Lit |
|---|---|---|
| The attribute's name. | The property's name with dashes: giftWrapped watches gift-wrapped. | The property's name in lowercase: teaName watches teaname. |
| A number from attribute text. | HTML's rules for numbers: "4 cups" reads as 4. | Number(): "4 cups" reads as NaN. |
A property set to the string "4". | It reads back as the number 4. | It stays the string "4". |
| When reflect writes the attribute. | At once, inside the setter. | During the next update. |
| The default. | fallback, which never becomes an attribute. | The constructor's value. It reflects, unless you add useDefault: true. |
| Internal state with no attribute. | There's no option for it. | state: true, or @state(). |
| The change check. | One hasChanged() method for every property. | A hasChanged option on each property, with notEqual as the default. |
Neither way is wrong. TeaElement copies built-in elements, which clean up a bad value. Lit keeps what you set. Its docs say @property() never alters a value, and suggest your own setter when you need to (Lit).
How does Lit decide that a property changed?
Each set runs a check: is the new value different from the old one? The option is called hasChanged. Its default is notEqual, which returns !Object.is(value, old) (reactive-element.ts, lines 403 and 404).
Lit's docs call it strict inequality, !== (Lit). The two differ for NaN: Object.is() treats NaN as the same as NaN. Your ReactiveTea made the same choice (lesson 18.1), and the equality lesson covers Object.is() in full. Lit behaves the same:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3"></tea-cup-rating><script type="module"> import { TeaCupRating } from "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; const draw = TeaCupRating.prototype.render; let renders = 0; TeaCupRating.prototype.render = function () { renders++; return draw.call(this); }; rating.value = NaN; await rating.updateComplete; rating.value = NaN; await rating.updateComplete; console.log(`Renders: ${renders}`);</script>- Lines 9 to 14 count the calls to
render(), as the playground of lesson 20.1 did. - Lines 15 to 18 set
NaNtwice, and wait for the update each time.
It prints Renders: 1. Only the first NaN was a change.
Why doesn't push() update a Lit component?
The check compares the value itself. For an array, that's the array, not what's in it. Lit's docs say that changing an object or an array in place doesn't trigger an update (Lit). Here an order, tea-extras, holds an extras array with attribute: false. Try three ways to add honey:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-extras></tea-extras><button id="add">Add honey</button><script type="module"> import { TeaExtras } from "./tea-extras.js"; const ticket = document.querySelector("tea-extras"); const draw = TeaExtras.prototype.render; let renders = 0; TeaExtras.prototype.render = function () { renders++; return draw.call(this); }; document.querySelector("#add").addEventListener("click", async () => { renders = 0; ticket.extras.push("honey"); // No new array, and no requestUpdate(). await ticket.updateComplete; console.log(`Renders: ${renders}`); });</script>Press Add honey. It prints Renders: 0, and the order still shows Extras: milk. The honey is in the array, but no setter ran.
- Lines 9 to 14 count the calls to
render(). - Lines 17 and 18 add the honey. They're the only lines that change.
- push():
Renders: 0. The order still showsExtras: milk. - A new array:
Renders: 1, andExtras: milk, honey. - push(), then requestUpdate():
Renders: 1, andExtras: milk, honey.
notEqual compares the new value with the old one using Object.is(). NaN matches NaN, and the same array matches itself, so only a new array gets an update. push() never even runs the setter.push() reads ticket.extras and changes that array. No setter runs. Even if one did, notEqual would see the same array: setting ticket.extras = ticket.extras draws nothing either. So you have two fixes, as in lesson 18.1:
- Give it a new array, as the second choice does. The
...copies the old items in. - Change it, then call
requestUpdate()with no arguments. That skips the check.
Lit's docs prefer new arrays. requestUpdate() redraws only this component. A child that got the same array won't see a change (Lit). The Lit Cheat Sheet gives the same two fixes (Lit).
How do you write your own hasChanged?
Give hasChanged as an option: a function that gets the new value and the old one, and returns true for a change. This one ignores half cups:
value: {
type: Number,
reflect: true,
hasChanged: (next, previous) => Math.floor(next) !== Math.floor(previous),
},Line 4: Math.floor() rounds down, so 3 and 3.5 both give 3. They count as the same.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3"></tea-cup-rating><button id="half">Half a cup more</button><script type="module"> import { TeaCupRating } from "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); const draw = TeaCupRating.prototype.render; let renders = 0; TeaCupRating.prototype.render = function () { renders++; return draw.call(this); }; document.querySelector("#half").addEventListener("click", async () => { renders = 0; rating.value += 0.5; await rating.updateComplete; console.log(`value ${rating.value}, renders ${renders}, attribute ${rating.getAttribute("value")}`); });</script>Line 17 adds half a cup on each press. Line 19 prints the value, the renders, and the attribute. The first press prints value 3.5, renders 0, attribute 3. The second prints value 4, renders 1, attribute 4.
Look at the first line again. The property holds 3.5, but the attribute still says 3. A set that hasChanged turns down gets no update at all (lines 1301 to 1318), and reflecting happens in updates. Why it matters: a custom check skips more than drawing. Use it only where skipping is safe.
How do you declare Lit properties without decorators?
Every JavaScript example so far did. Plain JavaScript can't use decorators, because no browser runs them (lesson 20.1). So two parts share the job, as Lit's docs show (Lit):
static propertiesmaps each name to its options, as@property()and@state()would.- The constructor sets the starting values, after
super().
Why does a class field stop a Lit property from updating?
A class field is a property each new object gets, written right in the class body. JavaScript adds it just after super() returns (lesson 4.2). It looks like a tidy place for defaults. Here are the rating's defaults as class fields, in place of lines 11 to 16:
value = 0;
max = 5;
hovered = 0;Lines 1 to 3 give each property its starting value, right in the class body. The constructor is gone.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3"></tea-cup-rating><button id="more">One more cup</button><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); document.querySelector("#more").addEventListener("click", async () => { rating.value += 1; await rating.updateComplete; console.log(`value: ${rating.value}, own property: ${Object.hasOwn(rating, "value")}`); });</script>Line 10 adds a cup. Line 12 prints the value, and whether value is the element's own property.
The rating shows ●●●○○. Press One more cup. It prints value: 4, own property: true, but the cups stay ●●●○○. Pointing at a cup does nothing either.
value on the element first. The class field put an own property there, so the search stops before the prototype, and Lit's setter never runs.Lit puts each getter and setter on the prototype (createProperty(), lines 698 to 725). The class field puts a plain value on the element itself. JavaScript finds the element's own property first, so every set lands there, and Lit's setter never runs. Lit's docs say that in JavaScript, you must not use class fields for reactive properties (Lit). TeaElement had the same trap (lesson 19.2).
How does Lit's development build help?
Nothing complained. That's Lit's production build, which esm.sh serves by default. Lit also ships a development build, with extra checks and warnings. You choose it with the development export condition (Lit), and esm.sh picks it with ?dev (esm.sh):
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3?dev" } }</script><tea-cup-rating value="3"></tea-cup-rating><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); try { await rating.updateComplete; } catch (error) { console.log(error.message); }</script>- Line 2 maps the name lit to Lit's development build.
- Lines 8 to 12 wait for the first update, and print its error.
The console first shows Lit's warning, Lit is in dev mode. Not recommended for production!, with a link. Then line 11 prints the error:
The following properties on element tea-cup-rating will not trigger updates as expected because they are set using class fields: value, max, hovered. Native class fields and some compiled output will overwrite accessors used for detecting changes. See https://lit.dev/msg/class-field-shadowing for more information.The rating draws nothing at all: Lit checks for these fields just before the first draw (lines 1452 to 1471). Why it matters: use the development build while you work. It turns a silent bug into an error that names each field.
What does noAccessor do?
noAccessor: true tells Lit not to make the getter and setter (lines 714 to 724). The attribute still sets the property, but nothing asks for an update. Your own code has to:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating value="3"></tea-cup-rating><script type="module"> import { TeaCupRating } from "./tea-cup-rating.js"; console.log(`An accessor for value: ${Object.hasOwn(TeaCupRating.prototype, "value")}`); const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; rating.setAttribute("value", "4"); await rating.updateComplete; console.log(`value ${rating.value}, cups ${rating.shadowRoot.textContent}`); rating.requestUpdate(); await rating.updateComplete; console.log(`value ${rating.value}, cups ${rating.shadowRoot.textContent}`);</script>- Line 7 checks the prototype for an accessor. The tab gives value
noAccessor: true. - Line 10 changes the attribute. Line 12 prints the value and the cups.
- Line 13 asks for an update by hand. Line 15 prints them again.
It prints An accessor for value: false, then value 4, cups ●●●○○, then value 4, cups ●●●●○.
Lit's docs call it rarely needed: it's for a subclass that changes the options of a property its parent class already made (Lit). Your own getter and setter don't need it. Lit wraps them, and still asks for the update (lines 754 to 794).
Should you use standard or experimental decorators with Lit?
In TypeScript, decorators make the rating shorter:
import { LitElement, html } from "lit";
import { customElement, property, state } from "lit/decorators.js";
@customElement("tea-cup-rating")
export class TeaCupRating extends LitElement {
@property({ type: Number, reflect: true }) value = 0;
@property({ type: Number }) max = 5;
@state() private hovered = 0;
render() {
const shown = this.hovered || this.value;
const cups = Array.from({ length: this.max }, (_, index) => (index < shown ? "●" : "○"));
return html`${cups.join("")}`;
}
}
declare global {
interface HTMLElementTagNameMap {
"tea-cup-rating": TeaCupRating;
}
}- Line 4 registers the tag, as in lesson 20.1.
- Lines 6 to 8 are the three declarations, each with its default right on the field.
- Lines 17 to 21 add the tag to
HTMLElementTagNameMap, so TypeScript knows the element's class.
But TypeScript has two kinds of decorators, and Lit takes both (Lit):
- Experimental decorators follow an early version of the proposal. Lit has used them from the start. They need
experimentalDecorators: true(the TypeScript decorators lesson). - Standard decorators follow the current TC39 proposal. TypeScript uses them when
experimentalDecoratorsis off.
One difference matters for Lit. A standard decorator can't change what kind of member it decorates (Lit). @property() needs a getter and a setter, and a field is neither. So standard decorators need the accessor keyword:
@property({ type: Number, reflect: true }) accessor value = 0;
@property({ type: Number }) accessor max = 5;
@state() private accessor hovered = 0;Lines 1 to 3 are lines 6 to 8 again, each with the word accessor before the name.
accessor makes an auto-accessor: a getter and setter on the prototype, with a private value behind them (auto-accessors). Lit's decorator wraps that getter and setter (property.ts, lines 139 to 161).
Leaf and Kettle wraps gifts at the counter. The wrapper folds paper around a box, but can't make a box. Bring a tin of tea in its box, and it comes back wrapped. Bring a loose scarf, and the wrapper hands it back.
- In real life: The gift wrapper at the counter
- In JavaScript: A standard decorator
- In real life: A box, with sides to fold paper around
- In JavaScript: The getter and setter that accessor makes
- In real life: A loose scarf, with no box
- In JavaScript: A plain field
- In real life: "Sorry, we can't wrap that"
- In JavaScript: Unsupported decorator location: field
The playground runs what TypeScript writes for four settings. The page is the same each time. Only the tea-cup-rating.js tab changes:
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3", "lit/": "https://esm.sh/lit@3.3.3/" } }</script><tea-cup-rating value="3"></tea-cup-rating><button id="more">One more cup</button><script type="module"> try { await import("./tea-cup-rating.js"); } catch (error) { console.log(`${error.name}: ${error.message}`); } const rating = document.querySelector("tea-cup-rating"); document.querySelector("#more").addEventListener("click", async () => { rating.value += 1; await rating.updateComplete; console.log(`value: ${rating.value}, cups: ${rating.shadowRoot?.textContent ?? "none"}`); });</script>Press One more cup. It prints value: 4, cups: ●●●●○. TypeScript moved each default into the constructor, and __decorate() handed Lit each field's name.
- Lines 7 to 11 load the compiled rating, and print the error if loading it throws.
- Lines 13 to 17 add a cup on each press, and print the value and the cups.
- Experimental:
value: 4, cups: ●●●●○. - Standard, with accessor:
value: 4, cups: ●●●●○, the same. - Standard, no accessor:
Error: Unsupported decorator location: fieldas soon as it loads. Thenvalue: NaN, cups: none. - Experimental, class fields:
value: 4, cups: ●●●○○. The value changed, and the cups didn't.
Read each row across: the settings, what you write on the field, and what happens.
| TypeScript settings | What you write | What happens |
|---|---|---|
experimentalDecorators: true and useDefineForClassFields: false. | @property() value = 0; | It works. Lit's docs recommend this for TypeScript. |
| Neither setting: standard decorators. | @property() accessor value = 0; | It works too, and TypeScript's output is much longer. |
| Neither setting: standard decorators. | @property() value = 0; | TypeScript reports error 1240, and Lit throws Unsupported decorator location: field. |
experimentalDecorators: true alone, with target: "ES2022". | @property() value = 0; | No error. But the fields hide Lit's accessors, so the cups never change. |
The third choice fails twice. First, TypeScript reports error 1240 on lines 6 to 8: "Unable to resolve signature of property decorator when called as an expression." Then, if you run its output anyway, Lit throws. A standard decorator on a field reaches the last line of Lit's standardProperty() (property.ts, line 170).
The fourth fails with no error at all. With target set to ES2022 or later, useDefineForClassFields is true unless you set it (TypeScript). Then TypeScript keeps the defaults as class fields: the trap from the last section. That's why Lit's docs pair experimental decorators with useDefineForClassFields: false (Lit).
Which kind should you pick?
- Lit's docs recommend experimental decorators for now, because standard ones compile to much more code (Lit). Compare the first two tabs: the experimental output is 34 lines, and the standard one is 88.
- With Babel, Lit takes only standard decorators, so always write
accessor(Lit). - Lit 3 is the first Lit with standard decorators. Examples written for Lit 2 put
@property()on plain fields. Addaccessorbefore you switch (Lit 3 upgrade guide). - Lit's decorators take
accessorin experimental mode too. So you can add it first, and change the settings later (Lit).
Adding a cup rating to the tea card
Now the rating goes where Asha wants it: inside the kit's tea card. This is the version with the converter and useDefault.
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><style> tea-cup-rating[value="5"] { outline: 2px solid goldenrod; border-radius: 8px; }</style><tea-card name="Sencha" price="4"> <p>Grassy and sweet. <tea-cup-rating value="4"></tea-cup-rating></p></tea-card><p id="saved">Rate this tea.</p><script type="module"> import "./tea-kit/index.js"; import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); rating.addEventListener("change", () => { document.querySelector("#saved").textContent = `Saved: ${rating.value} cups`; });</script>- Lines 4 to 9 are a page style for a five-cup rating. It reads the reflected attribute.
- Lines 10 to 12 are the kit's
tea-card, with the rating in its tasting notes. - Lines 18 to 20 save the rating on each
changeevent.
The card shows Sencha and Price: 4, with ●●●●○ in its notes. Click the fifth cup. The page says Saved: 5 cups, and a gold outline appears around the cups.
The outline is reflection at work. Page CSS can't see a property, but it can see an attribute. That's why value reflects and hovered doesn't. Why it matters: reflect what the page needs to style or select, and keep the rest as plain properties or state.
Now sort some properties. Which kind should each one be?
value: the rating the page writes in HTMLmax: how many cups to draw, set in HTMLdisabled: a switch the page turns on, which page CSS styleshovered: the cup under the pointeropen: whether the rating's own menu is openloading: whether the rating's own fetch is still runningnotes: an array the page hands in from JavaScripttea: an object with a name and a price, from JavaScript
Sort each property of a rating by how you'd declare it.
Common mix-ups
- "@state() makes a property private." No. The page read
hovered: 0from outside. State only has no attribute. Mark itprivatein TypeScript. - "type: Number checks the value." No. It only reads attribute text. Setting
"4"stored a string. - "reflect writes the attribute as soon as you set the property." No. Lit writes it in the next update. Right after the set, the attribute still said 3.
- "useDefault keeps bad values out." No. It keeps the default off the page and brings it back when the attribute goes.
value="lots"still givesNaN. - "push() into an array property redraws the component." No. It printed
Renders: 0. Give it a new array, or callrequestUpdate(). - "Lit compares with !==, so NaN always looks new." No.
notEqualusesObject.is(). Two sets ofNaNdrew once. - "A class field is a fine place for a Lit default in JavaScript." No. It hides Lit's setter, and the cups stopped changing. Set defaults in the constructor.
- "@property() works on a plain field with standard decorators." No. It needs
accessor. Without it, Lit throwsUnsupported decorator location: field.
Practice exercises
What does the console print?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<script type="module">
import { LitElement } from "lit";
class TeaPot extends LitElement {
static properties = {
teaName: {},
roast: { attribute: "roast-level" },
open: { state: true },
notes: { attribute: false },
};
}
customElements.define("tea-pot", TeaPot);
console.log(TeaPot.observedAttributes.join(", "));
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><script type="module"> import { LitElement } from "lit"; class TeaPot extends LitElement { static properties = { teaName: {}, roast: { attribute: "roast-level" }, open: { state: true }, notes: { attribute: false }, }; } customElements.define("tea-pot", TeaPot); console.log(TeaPot.observedAttributes.join(", "));</script>It prints teaname, roast-level. teaName watches its lowercase name, and roast watches roast-level. open is state, and notes has attribute: false, so neither is in the list.
The rating's max has type: Number. What does the console print, in order?
<script type="importmap">
{ "imports": { "lit": "https://esm.sh/lit@3.3.3" } }
</script>
<tea-cup-rating></tea-cup-rating>
<script type="module">
import "./tea-cup-rating.js";
const rating = document.querySelector("tea-cup-rating");
rating.setAttribute("max", "4");
console.log(typeof rating.max);
rating.max = "4";
console.log(typeof rating.max);
</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cup-rating></tea-cup-rating><script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); rating.setAttribute("max", "4"); console.log(typeof rating.max); rating.max = "4"; console.log(typeof rating.max);</script>It prints number, then string. The attribute's text went through the converter, which called Number(). The property set on line 10 skipped the converter, so the string stayed a string.
Press Add lemon. The order still shows Extras: milk. Fix the page. What does the order show then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-extras></tea-extras><button id="lemon">Add lemon</button><script type="module"> import "./tea-extras.js"; const ticket = document.querySelector("tea-extras"); document.querySelector("#lemon").addEventListener("click", () => { ticket.extras.push("lemon"); });</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-extras></tea-extras><button id="lemon">Add lemon</button><script type="module"> import "./tea-extras.js"; const ticket = document.querySelector("tea-extras"); document.querySelector("#lemon").addEventListener("click", () => { ticket.extras = [...ticket.extras, "lemon"]; });</script>Only line 10 of the page changes: it gives extras a new array. The setter runs, notEqual sees a different array, and Lit draws Extras: milk, lemon.
tea-steep shows Steep for 2:30 seconds, and Ten seconds more makes it 2:3010. In the tea-steep.js tab, write a converter so time="2:30" means 150 seconds. What does the console print after Ten seconds more?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-steep time="2:30"></tea-steep><button id="more">Ten seconds more</button><script type="module"> import "./tea-steep.js"; const steep = document.querySelector("tea-steep"); document.querySelector("#more").addEventListener("click", async () => { steep.seconds += 10; await steep.updateComplete; console.log(`time attribute: ${steep.getAttribute("time")}`); });</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-steep time="2:30"></tea-steep><button id="more">Ten seconds more</button><script type="module"> import "./tea-steep.js"; const steep = document.querySelector("tea-steep"); document.querySelector("#more").addEventListener("click", async () => { steep.seconds += 10; await steep.updateComplete; console.log(`time attribute: ${steep.getAttribute("time")}`); });</script>Only the tea-steep.js tab changes: a timeConverter object, and converter: timeConverter on seconds. 2:30 reads as 150 seconds, so the page shows Steep for 150 seconds. Ten seconds more makes 160, and reflecting writes it back as 2:40.
The button says Cups: 0, however often you click it. Fix the tea-cups.js tab. What does it show after two clicks?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cups></tea-cups><script type="module" src="./tea-cups.js"></script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><tea-cups></tea-cups><script type="module" src="./tea-cups.js"></script>Only the tea-cups.js tab changes: the class field cups = 0 becomes a constructor that sets this.cups = 0. Now each click runs Lit's setter, so two clicks show Cups: 2.
The page style adds "Rated" after each rating with a value attribute. Assam was never rated, but it says Rated too, and the console prints Rated teas: 2. Fix the rating. What does the console print then?
<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><style> tea-cup-rating[value]::after { content: " Rated"; }</style><p>Sencha <tea-cup-rating value="4"></tea-cup-rating></p><p>Assam <tea-cup-rating></tea-cup-rating></p><script type="module"> import "./tea-cup-rating.js"; const ratings = [...document.querySelectorAll("tea-cup-rating")]; await Promise.all(ratings.map((rating) => rating.updateComplete)); console.log(`Rated teas: ${document.querySelectorAll("tea-cup-rating[value]").length}`);</script><script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } }</script><style> tea-cup-rating[value]::after { content: " Rated"; }</style><p>Sencha <tea-cup-rating value="4"></tea-cup-rating></p><p>Assam <tea-cup-rating></tea-cup-rating></p><script type="module"> import "./tea-cup-rating.js"; const ratings = [...document.querySelectorAll("tea-cup-rating")]; await Promise.all(ratings.map((rating) => rating.updateComplete)); console.log(`Rated teas: ${document.querySelectorAll("tea-cup-rating[value]").length}`);</script>Only line 5 of the tea-cup-rating.js tab changes: value gets useDefault: true. The starting 0 no longer reflects, so Assam keeps no value attribute, the page style skips it, and the console prints Rated teas: 1.
Check your understanding
Question 1 of 8The rating declares
hovered: { state: true }. What does that change, next to a public property?Choose an answer to see the explanation.
Question 2 of 8The rating starts with
value="3". What does this reflect page print?Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } } </script> <tea-cup-rating value="3"></tea-cup-rating> <script type="module"> import "./tea-cup-rating.js"; const rating = document.querySelector("tea-cup-rating"); await rating.updateComplete; rating.value = 4; console.log(`Right after: ${rating.getAttribute("value")}`); await rating.updateComplete; console.log(`After the update: ${rating.getAttribute("value")}`); </script>Choose an answer to see the explanation.
Question 3 of 8What does the push() choice of the arrays playground print after one press of Add honey?
Read the code, then predict<script type="importmap"> { "imports": { "lit": "https://esm.sh/lit@3.3.3" } } </script> <tea-extras></tea-extras> <button id="add">Add honey</button> <script type="module"> import { TeaExtras } from "./tea-extras.js"; const ticket = document.querySelector("tea-extras"); const draw = TeaExtras.prototype.render; let renders = 0; TeaExtras.prototype.render = function () { renders++; return draw.call(this); }; document.querySelector("#add").addEventListener("click", async () => { renders = 0; ticket.extras.push("honey"); // No new array, and no requestUpdate(). await ticket.updateComplete; console.log(`Renders: ${renders}`); }); </script>Choose an answer to see the explanation.
Question 4 of 8The rating's value is NaN, and the page sets it to NaN again. Does Lit update?
Choose an answer to see the explanation.
Question 5 of 8In plain JavaScript, a Lit rating declares value in static properties and also writes
value = 0;as a class field. What happens?Choose an answer to see the explanation.
Question 6 of 8Why do Lit's decorators need
accessorwith standard decorators?Choose an answer to see the explanation.
Question 7 of 8The rating has
useDefault: trueon value. The page removes the value attribute. What is value then?Choose an answer to see the explanation.
Question 8 of 8value has
type: Number. The page runsrating.value = "4". What istypeof rating.value?Choose an answer to see the explanation.
Key takeaways
- Declare reactive properties in static properties, or with @property() and @state() in TypeScript.
- Lit makes a getter and setter for each one. Setting it draws the component again.
- A public property watches its name in lowercase. attribute gives another name, or false for none.
- State never gets an attribute. Only the component should set it.
- type is a hint for reading attribute text. A converter reads and writes it your own way.
- reflect writes the attribute during the next update. useDefault keeps the default off the page.
- hasChanged uses Object.is() by default. push() never updates: give a new array, or call requestUpdate().
- In JavaScript, set defaults in the constructor. A class field hides Lit's setter.
- Standard decorators need accessor. Experimental ones need useDefineForClassFields: false.
Remember the one-liner.
The property is the tea in the pot, and the attribute is its label. Lit reads the label on every change, and rewrites it only when you ask it to reflect.
Sources
The facts on this page come from these docs and source files:
- Reactive properties, Lit.
- reactive-element.ts, at lit 3.3.3, Lit.
- state.ts, at lit 3.3.3, Lit.
- The Lit Cheat Sheet, Elliott Marquez, Lit.
- The lit package's changelog, at 3.3.3, Lit.
- ReactiveElement API reference, Lit.
- Development, Lit.
- esm.sh's README: development build, esm.sh.
- Decorators, Lit.
- Lit 3 upgrade guide, Lit.
- property.ts, at lit 3.3.3, Lit.
- experimentalDecorators, TypeScript.
- useDefineForClassFields, TypeScript.
- browser-compat-data, MDN.
Support data comes from MDN's browser-compat-data.
Coming next: Lit templates, the next lesson of the Lit stage. It covers the bindings this lesson only used: @ for events, and more for attributes and properties.