Root state and derived state form a graph of values with no side effects. This guide covers how data enters the graph, how results leave it, and which Ember tool does each job.
- Inputs write to root state. Event handlers, response callbacks, subscription messages, and timers are inputs.
- Outputs read the graph and act on the world. The renderer is the main output.
Everything between an input and an output is a derivation, and derivations have no side effects.
Rendering Is the Effect
Some reactive systems provide an effect primitive. An effect is a function that runs again whenever a reactive value it read changes. Effects in other frameworks have different timings. Some even run synchronously after an "output" calculation, which may cause further "output" calculations. Ember does not provide an effect primitive because the renderer does this job.
A template is a set of effects.
Each {{expression}} and each attribute binding tells the renderer to update one part of the DOM when the values it reads change.
The renderer batches these updates, schedules them before the browser paints, and updates only the DOM whose inputs changed.
Why There Is No Effect Primitive
A general effect primitive has four problems:
- An effect runs on every change to its inputs, whether or not anything needs the result. The rest of the system is lazy (an ideal performance-related trait), and effects undo that.
- When one change triggers several effects, the order they run in is not specified. Code that depends on that order has a bug.
- Effects that write state fall out of sync. An effect that copies X into Y leaves Y stale until the effect runs, and Y can disagree with X. If the write triggers another effect, the effects cascade or loop. Derive Y from X with a getter instead, as described in Derived State. The backtracking assertion reports a write during a derivation as an error.
- Derived values belong in getters. DOM manipulation belongs in a modifier. Processes such as subscriptions belong to an owner, with cleanup. Ember provides a tool for each, described below.
Managed Effects: Attached to a Lifetime
When your code must act on the world, use a tool that ties the work to a lifetime. The work starts when the lifetime starts, cleans up when it ends, and runs again through autotracking like everything else.
A modifier is an effect scoped to a DOM element. Modifiers should be used sparingly, and should avoid setting tracked state. A modifier runs when the element renders. It cleans up and runs again when tracked state it consumed changes. It cleans up when the element is removed:
import { modifier } from 'ember-modifier';
import Chart from 'chart.js/auto';
export default modifier((element, [data]) => {
let chart = new Chart(element, { type: 'bar', data });
return () => chart.destroy();
});
import drawChart from 'my-app/modifiers/draw-chart';
<template>
<canvas {{drawChart @chartData}}></canvas>
</template>
The modifier runs again when @chartData changes.
It cannot run before the element exists, and it cannot leak after the element is gone.
The template shows where its effect lands.
Template Lifecycle, DOM, and Modifiers covers modifiers in detail.
A destroyable covers work with no element.
Any object that Ember destroys, such as a component, a service, or a class-based helper, can register cleanup with registerDestructor from @ember/destroyable:
import Service from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { registerDestructor } from '@ember/destroyable';
export default class ClockService extends Service {
@tracked now = new Date();
constructor(...args) {
super(...args);
let timer = setInterval(() => {
this.now = new Date();
}, 1000);
registerDestructor(this, () => clearInterval(timer));
}
}
Any getter in the application can now derive from clock.now.
Seconds remaining, whether a store is open, and a formatted timestamp all update each second.
The interval and its cleanup live in one place.
Setup, cleanup, and reactive state together are called a resource. The ember-resources library provides resources as values for components and templates. A service with a destructor, as above, is the same pattern with no dependencies.
Inputs: Writing into the Graph from Outside
Code that runs outside the graph writes to root state. Event handlers, socket callbacks, timers, and promise callbacks all work this way:
this.socket.addEventListener('message', (event) => {
// lastMessage is a tracked property
this.lastMessage = JSON.parse(event.data);
});
A write from outside the graph is always allowed. The backtracking assertion restricts writes only during a reactive computation, that is, inside a getter or a template. An event callback is not a computation, so it can write as many properties as it needs to. The writes are batched into one rerender.
The clock service above shows the full input pattern.
An external process, the interval, writes to one tracked property, and cleanup is bound to a lifetime.
Subscriptions, ResizeObservers, and BroadcastChannels follow the same steps.
Async: Tracking Stops at await
Tracking today is synchronous.
The system records reads that happen while a template expression or a cached getter computes.
A computation ends at the first await.
Code after an await, inside setTimeout, or in a .then() callback runs later, outside the computation that started it.
Reads in that code are not consumed:
// The renderer cannot see through this
get userName() {
return fetch(`/users/${this.userId}`).then((r) => r.json()); // a Promise, not a name
}
A derivation must return its value synchronously. To handle async work, treat the request as an input. The request is a side effect, and its progress is root state. Start the request at a lifetime boundary, and write each phase into tracked properties:
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
class RequestState {
@tracked status = 'pending';
@tracked value = null;
@tracked error = null;
get isPending() {
return this.status === 'pending';
}
constructor(promise) {
promise.then(
(value) => {
this.value = value;
this.status = 'resolved';
},
(error) => {
this.error = error;
this.status = 'rejected';
}
);
}
}
export default class Profile extends Component {
user = new RequestState(
fetch(`/users/${this.args.userId}`).then((response) => response.json())
);
<template>
{{#if this.user.isPending}}
Loading…
{{else if this.user.error}}
Something went wrong.
{{else}}
Hello, {{this.user.value.name}}!
{{/if}}
</template>
}
The async state is now data.
The loading message is a derivation like any other, an {{#if}} on a tracked property.
The class above holds status, value, and error as reactive fields.
Libraries such as reactiveweb (getPromiseState) and WarpDrive (getRequestState / getPromiseState) provide this as a utility that covers more use cases, and is better suited to general use.
The above example has a problem, however -- the request is created in a field initializer, so it reads userId once and does not fetch again when the argument changes.
Deferring Consumption describes this snapshot problem.
To run an effect again when its inputs change, use one of the managed tools above: a modifier when an element is involved, or a resource otherwise.