Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Tracked State and Reactivity

Tracked Collections and Immutable Updates

Update arrays, objects, maps and sets so Ember re-renders: the replace-by-copy pattern, tracked-built-ins collections, tracked classes, and how to choose between them.

@tracked notices when you assign to a field. Arrays, objects, maps and sets are different: they are containers, and you can change what is inside without assigning to the field that holds them. items.push(x) changes the array but never touches this.items, so Ember sees nothing. This lesson covers the two ways to get reliable updates for collections: replace the whole value with a changed copy, or use tracked collections that report their own changes.

Real Ember vs stand-in. File-named blocks are real Ember code (read-only). The runnable blocks are plain-JavaScript models so you can try the patterns without a build.

The problem

app/components/todo-list.gjs

JavaScript
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { on } from '@ember/modifier';

export default class TodoList extends Component {
  @tracked items = ['Learn Ember'];

  @action
  addBroken() {
    this.items.push('New item'); // changes the array, not the field
  }

  <template>
    <ul>{{#each this.items as |item|}}<li>{{item}}</li>{{/each}}</ul>
    <button type="button" {{on "click" this.addBroken}}>Add</button>
  </template>
}

Clicking Add changes the array in memory, but the list on the screen does not change: the field items still points to the same array, so its revision never moved. Two fixes follow.

Fix 1: replace instead of mutate

Create a new array (or object) with the change applied and assign it. This is the simplest approach and needs nothing extra:

JavaScript
@action add(text) {
  this.items = [...this.items, text];              // add
}
@action remove(text) {
  this.items = this.items.filter((i) => i !== text); // remove
}
@action rename(index, text) {
  this.items = this.items.map((item, i) => (i === index ? text : item)); // update
}
@action update(user, changes) {
  this.user = { ...this.user, ...changes };        // objects: spread a copy
}

These patterns are called immutable updates: you never change the old value, you build a new one. They also make it obvious when something changed, and they work well with @cached because a new reference signals a new input. The cost is copying; for lists of a few thousand items this is fast, but for huge collections or very frequent updates, prefer a tracked collection.

Here is a runnable comparison. The Tracked helper stands in for @tracked: it only notices assignments.

JS Stand-in: why push is not noticed

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

No output.

Fix 2: tracked collections

The tracked-built-ins addon (ember install tracked-built-ins) provides drop-in classes whose own methods report changes:

Class Replaces Notes
TrackedArray Array push, splice, index assignment, sort and so on are all noticed
TrackedObject {} adding, changing and deleting keys is noticed
TrackedMap Map get, set, delete, has, iteration
TrackedSet Set add, delete, has, iteration
TrackedWeakMap, TrackedWeakSet their weak versions for keys that should be garbage collected

app/components/todo-list.gjs

JavaScript
import Component from '@glimmer/component';
import { TrackedArray } from 'tracked-built-ins';
import { action } from '@ember/object';
import { on } from '@ember/modifier';

export default class TodoList extends Component {
  items = new TrackedArray(['Learn Ember']);

  @action
  add() {
    this.items.push('New item'); // noticed: TrackedArray reports it
  }

  <template>
    <ul>{{#each this.items as |item|}}<li>{{item}}</li>{{/each}}</ul>
    <button type="button" {{on "click" this.add}}>Add</button>
  </template>
}

Note that items is not marked @tracked here, because nothing assigns to the field; the collection itself tracks its contents. The addon also exports helper functions (trackedArray([...]), trackedMap(...)) if you prefer them over new.

How can a plain-looking array notice mutations? It wraps the original so that reading an element records a read, and writing an element bumps a revision. The model below does the same with a JavaScript Proxy.

JS Stand-in: a tiny TrackedArray with a Proxy

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

No output.

The real library is far more precise (it tracks individual indexes and keys so unrelated reads do not re-render), but the principle is the same: collection operations bump revisions.

Tracked classes: objects with several fields

For a domain object with its own fields, such as a todo item, the simplest tool is a plain class with @tracked fields. Then editing an item re-renders exactly what displays that item, without copying the whole list:

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

export class Todo {
  @tracked title;
  @tracked done = false;

  constructor(title) {
    this.title = title;
  }

  toggle() {
    this.done = !this.done;
  }
}

A list component then holds new TrackedArray([new Todo('Learn Ember')]). Pushing re-renders the list; toggling an item re-renders only that item's text. This combination (tracked collection of tracked objects) is the most common shape for editable lists.

Choosing between the approaches

Situation Use
Small list or object, updated occasionally replace with a copy ([...items, x])
List updated often or very large TrackedArray
Keyed lookups (by id) TrackedMap or TrackedObject
Unique values (selected ids) TrackedSet
Items edited in place (checkbox, rename) class with @tracked fields
Data coming from Ember Data records are already tracked; the store gives you tracked arrays

Mixing is fine and common. What you must avoid is mutating a plain array or object that sits in a plain or @tracked field and expecting the screen to follow.

Index assignment on a plain array (items[0] = 'x') and delete obj.key on a plain object are invisible to Ember, even when the array sits in a @tracked field. Use splice/map/spread, or a tracked collection.

A selection set

Here is the Set case in a runnable model: toggling ids in a selection, and deriving a count and a label. A real TrackedSet behaves the same way, and the derived getters would update the screen automatically.

JS Stand-in: selection with a Set and derived values

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. this.items is @tracked and holds an array. Why does this.items.push('x') not update the screen?

    @tracked watches assignments to the field. push mutates the array in place without assigning.
  2. 2. Which line is an immutable update that Ember will notice?

    Assigning a new array to the tracked field is noticed. The other lines mutate the existing array.
  3. 3. What is different about using a TrackedArray?

    Tracked collections report their own mutations, so you can use normal mutating methods.
  4. 4. A list of todo items where each one has a checkbox. Which design re-renders the least?

    With tracked fields on each item, toggling one item re-renders only what displays that item.

Summary

  • @tracked sees assignments, not in-place changes to arrays, objects, maps or sets.
  • Immutable updates (spread, filter, map) are the simplest fix for small data.
  • TrackedArray, TrackedObject, TrackedMap and TrackedSet from tracked-built-ins let you mutate normally and still re-render.
  • For editable items, use a class with @tracked fields, optionally inside a tracked collection.

Next: Reactivity Pitfalls and Debugging