Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Tracked State and Reactivity

Derived State: Getters and @cached

Compute values from tracked state with plain getters, learn when a getter reruns, and use @cached to avoid repeated expensive work, with a runnable memoizer.

Most of what a screen shows is not stored directly; it is derived. A cart total comes from the items. A filtered list comes from the full list plus a search term. A full name comes from first and last. In Ember you express derived state with ordinary JavaScript getters. No special computed-property API, no dependency list: autotracking handles it.

This lesson shows how getters stay up to date, when they run, how to keep expensive ones from running more than needed with @cached, and how to decide between storing a value and deriving it.

Real Ember vs stand-in. Blocks with a file name are real Ember code and read-only here. Runnable blocks are plain-JavaScript models that reproduce the behavior.

Native getters just work

A getter that reads tracked fields is itself tracked, with no extra markup:

app/components/price-summary.gjs

JavaScript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';

export default class PriceSummary extends Component {
  @tracked items = [
    { name: 'Notebook', price: 6, qty: 2 },
    { name: 'Pen', price: 2, qty: 5 },
  ];
  @tracked taxRate = 0.2;

  get subtotal() {
    return this.items.reduce((sum, item) => sum + item.price * item.qty, 0);
  }

  get total() {
    return this.subtotal * (1 + this.taxRate);
  }

  <template>
    <p>Subtotal: {{this.subtotal}}</p>
    <p>Total: {{this.total}}</p>
  </template>
}

total reads subtotal, which reads items, and also reads taxRate. Changing either items or taxRate re-renders the paragraphs that depend on it. The chain of getters is followed automatically.

When does a getter run?

A plain getter is just a function call. It runs every time it is read, and a template that reads {{this.total}} three times calls it three times in the same render. Ember re-renders a part of the page only when a tracked value the getter read has changed, so during a normal re-render it runs once per place that reads it.

For cheap work (adding numbers, joining two strings) this is fine, and you should not worry. For expensive work, such as sorting 5,000 rows, filtering with a regular expression, or building a big structure, repeating it is wasteful.

@cached: remember the result

@cached memoizes a getter. The first read runs the getter and stores the result along with the tracked values it read. Later reads return the stored result as long as none of those tracked values changed. When one changes, the next read recomputes.

app/components/product-list.gjs

JavaScript
import Component from '@glimmer/component';
import { tracked, cached } from '@glimmer/tracking';

export default class ProductList extends Component {
  @tracked products = [];
  @tracked query = '';

  @cached
  get visibleProducts() {
    const q = this.query.toLowerCase();
    return this.products
      .filter((product) => product.name.toLowerCase().includes(q))
      .sort((a, b) => a.name.localeCompare(b.name));
  }

  <template>
    <p>{{this.visibleProducts.length}} products</p>
    <ul>
      {{#each this.visibleProducts as |product|}}
        <li>{{product.name}}</li>
      {{/each}}
    </ul>
  </template>
}

Here visibleProducts.length and the {{#each}} both read the getter, but the filter and sort run once per change of products or query. The model below shows a cached getter working with the revision counters from the previous lesson: it records which cells it read and recomputes only when one is newer.

JS Stand-in: a @cached memoizer

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The function runs only when one of the cells it read has changed. With a plain getter the counter would have gone up on every read.

Do not sprinkle @cached everywhere. A cache has a cost too (storing the result, checking its dependencies). Add it when a getter is expensive and read more than once; otherwise a plain getter is simpler and just as correct.

Derive instead of store

A very common beginner mistake is storing a value that could be computed, then trying to keep both in sync:

JavaScript
// Fragile: two sources of truth
@tracked items = [];
@tracked itemCount = 0;

add(item) {
  this.items = [...this.items, item];
  this.itemCount++; // easy to forget in some other method
}
JavaScript
// Better: one source of truth
@tracked items = [];

get itemCount() {
  return this.items.length;
}

A derived value cannot go stale, because it is recomputed from the state it derives from. Reach for a getter whenever a value is a pure function of other state: totals, counts, filtered lists, labels, validation flags, isEmpty, canSubmit.

The same idea works for form validation. Compute the errors from the current field values, and canSubmit becomes a one-liner:

JS Stand-in: derived validation state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In a real component, the three fields would be @tracked and the button would use disabled={{not this.canSubmit}} (or the equivalent helper). No code anywhere says "when email changes, update canSubmit": the dependency is the read.

Getters in templates: keep them pure

A getter used in a template (or any tracked context) should be pure: it returns a value from existing state and changes nothing. Do not set tracked properties inside a getter. Ember will raise an error like "You attempted to update x on Y, but it had already been used previously in the same computation" because rendering would depend on a value it is in the middle of changing. The reactivity pitfalls lesson shows this error and its fixes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does a plain native getter in an Ember component stay up to date?

    Any tracked field a getter reads becomes a dependency of whatever reads the getter, so changes flow through without declarations.
  2. 2. What does @cached change about a getter?

    @cached memoizes by the tracked values read during the computation. Unchanged inputs mean the stored result is returned.
  3. 3. When is @cached most worthwhile?

    Caching trades memory and bookkeeping for time, so it pays off for costly, repeatedly read results.
  4. 4. A component stores both items and itemCount and updates them in different methods. What is the better design?

    One source of truth avoids values drifting apart. A getter that derives the count can never be stale.

Summary

  • Derived state is written as native getters; autotracking follows the tracked reads inside them.
  • A plain getter runs on every read; add @cached for expensive getters read repeatedly.
  • Prefer deriving values over storing them, so there is a single source of truth.
  • Getters used in templates must be pure: they read state and never set tracked properties.

Next: Tracked Collections and Immutable Updates