Module 18 - Events and reactiveUtils

Level 4 ยท Interaction ยท ๐ŸŸก ยท 4 hours ยท Prereq: Module 17


What you'll build

A HandleRegistry class that makes leaking a listener structurally impossible, and an extent-driven statistics panel that recomputes only when the view settles - the two patterns that every interactive map application needs.


Why this matters

Every subscription in the SDK returns a handle. Forget to remove one and the closure stays alive, and with it the view, the layers, and every downloaded feature. In a single-page app with route changes, that is a hard memory leak measured in tens of megabytes per navigation.

It is also the #1 source of the "my app gets slower the longer it runs" bug, and it is entirely preventable with one class and one discipline.


Concepts

1. Two subscription systems

// DOM-like events - discrete things that happen
const h1 = view.on("click", handler);
const h2 = layer.on("edits", handler);
const h3 = sketchViewModel.on("create", handler);

// Property observation - state that changes
const h4 = reactiveUtils.watch(() => view.zoom, handler);
const h5 = reactiveUtils.when(() => view.stationary, handler);
const h6 = reactiveUtils.whenOnce(() => view.ready);

Both return a handle with .remove(). That's the invariant. Every single one.

2. View events

Event Fires Payload highlights
click Single click/tap mapPoint, x, y, button
double-click same
immediate-click Before the click/double-click distinction resolves same
pointer-down / -up / -move / -enter / -leave Raw pointer x, y, pointerType
drag Drag gesture action: "start"|"update"|"end", origin
key-down / key-up Keyboard, when the view has focus key
mouse-wheel Wheel deltaY
hold Long press mapPoint
layerview-create A LayerView is ready layer, layerView
layerview-create-error A LayerView failed layer, error
resize Container resized width, height

event.stopPropagation() prevents the view's default behaviour. Use it when your handler consumed the interaction:

view.on("click", (event) => {
  if (drawingMode) {
    event.stopPropagation();   // don't also open a popup
    addVertex(event.mapPoint);
  }
});

Event ordering matters for custom tools. Registering an immediate-click handler to open something will conflict with the default click behaviour that also opens popups. Prefer click unless you specifically need to pre-empt.

3. reactiveUtils - the four functions

import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";

// watch - run on every change
reactiveUtils.watch(
  () => view.zoom,                          // getter (tracked)
  (zoom, oldZoom) => console.log(zoom),     // callback
  { initial: true }                          // fire once immediately
);

// when - run when the getter becomes truthy
reactiveUtils.when(
  () => view.stationary,
  () => recomputeStatistics()
);

// whenOnce - resolve a Promise the first time the getter is truthy
await reactiveUtils.whenOnce(() => view.popup);

// on - subscribe to an event on an object that may not exist yet
reactiveUtils.on(
  () => view.popup,      // the target, resolved reactively
  "trigger-action",      // the event
  (event) => handleAction(event)
);

reactiveUtils.on is the elegant solution to "the object doesn't exist yet." Module 11 used whenOnce(() => view.popup) then .on(...); reactiveUtils.on does both, and re-subscribes if the target is replaced.

4. How dependency tracking works

The getter runs inside a tracking context. Every Accessor property read during that call registers as a dependency.

// โœ… view.zoom is READ inside the getter - tracked
reactiveUtils.watch(() => view.zoom, onZoom);

// โœ… multiple properties, all tracked
reactiveUtils.watch(
  () => [view.zoom, view.center, view.rotation],
  ([zoom, center, rotation]) => update(zoom, center, rotation)
);

// โŒ read outside the getter - never fires again
const z = view.zoom;
reactiveUtils.watch(() => z, onZoom);

// โŒ conditional read - if the first branch is taken, view.center is never tracked
reactiveUtils.watch(
  () => (view.zoom > 10 ? view.zoom : view.center),
  onChange
);

The conditional case is the subtle one. Tracking is established by what the getter actually reads on that invocation. Read both properties unconditionally and branch in the callback.

5. Options

reactiveUtils.watch(getter, callback, {
  initial: true,        // fire once at setup with the current value
  once: true,           // remove the handle after the first callback
  equals: (a, b) => a === b,   // custom equality; default is a shallow/structural check
  sync: false,          // true = fire synchronously; default batches to the next tick
});

Leave sync: false. Synchronous callbacks fire mid-update and can observe inconsistent state. The batched default is almost always what you want.

6. view.stationary - the property that saves your quota

// โŒ fires on every animation frame during a pan - dozens of queries per second
reactiveUtils.watch(() => view.extent, () => queryVisibleFeatures());

// โœ… fires twice per interaction: false when movement starts, true when it settles
reactiveUtils.when(() => view.stationary, () => queryVisibleFeatures());

Anything expensive - a service query, a statistics recomputation, a URL update, an analytics event - belongs behind stationary, not behind extent.

7. updating - knowing when the map is busy

reactiveUtils.watch(
  () => view.updating,
  (updating) => { spinner.hidden = !updating; }
);

// Per-layer
const layerView = await view.whenLayerView(layer);
reactiveUtils.watch(() => layerView.updating, (u) => { โ€ฆ });

view.updating is true while anything is loading - tiles, features, layers. It is the correct signal for a loading indicator, and it composes: no need to track individual requests.

8. Cleanup discipline

Three patterns, in increasing robustness:

// 1. Manual - fine for two handles, fragile beyond that
const handles = [];
handles.push(view.on("click", onClick));
handles.push(reactiveUtils.watch(() => view.zoom, onZoom));
handles.forEach((h) => h.remove());

// 2. Handles.add - the SDK's own owner
import Handles from "@arcgis/core/core/Handles.js";
const handles = new Handles();
handles.add(view.on("click", onClick), "tool");
handles.add(reactiveUtils.watch(() => view.zoom, onZoom), "tool");
handles.remove("tool");        // remove by group
handles.destroy();             // remove everything

// 3. A registry that makes forgetting impossible - built below

Handles is underused. It ships with the SDK, groups handles by a key, and is exactly what you want for "this tool's subscriptions."


Build it

Step 1 - HandleRegistry

// src/handleRegistry.js

/**
 * Owns every subscription made on behalf of one feature/tool/component.
 *
 * The point is that `subscribe` is the ONLY way to create a handle, so a
 * handle cannot exist without being owned. That turns "remember to clean up"
 * from a discipline into a property of the API.
 */
export class HandleRegistry {
  #handles = new Map();   // group -> Set<handle>
  #destroyed = false;

  /**
   * @param {{remove: () => void}} handle  anything the SDK returned
   * @param {string} [group]               for partial teardown
   * @returns {{remove: () => void}}       the same handle, for chaining
   */
  add(handle, group = "default") {
    if (this.#destroyed) {
      // Adding to a destroyed registry means a race - the component unmounted
      // while an async setup was still running. Remove immediately rather than
      // leaking, and say so.
      handle.remove();
      console.warn("HandleRegistry: handle added after destroy; removed immediately.");
      return handle;
    }
    if (!this.#handles.has(group)) this.#handles.set(group, new Set());
    this.#handles.get(group).add(handle);
    return handle;
  }

  /** Remove every handle in a group. */
  removeGroup(group) {
    const set = this.#handles.get(group);
    if (!set) return;
    for (const handle of set) safeRemove(handle);
    set.clear();
    this.#handles.delete(group);
  }

  /** Remove everything. Safe to call twice. */
  destroy() {
    for (const set of this.#handles.values()) {
      for (const handle of set) safeRemove(handle);
    }
    this.#handles.clear();
    this.#destroyed = true;
  }

  get size() {
    let n = 0;
    for (const set of this.#handles.values()) n += set.size;
    return n;
  }
}

function safeRemove(handle) {
  try {
    handle.remove();
  } catch (error) {
    // A handle whose target was already destroyed can throw. That's not a
    // reason to abandon the rest of the teardown.
    console.warn("HandleRegistry: handle.remove() threw", error);
  }
}

The #destroyed check is not paranoia. In an async setup - const lv = await view.whenLayerView(layer); registry.add(lv.watch(...)) - the component can unmount during the await. Without the guard, that handle is created after teardown and leaks forever. This is one of the most common React + SDK bugs and Module 37 revisits it.

safeRemove catching matters because view.destroy() invalidates handles; removing them afterwards throws, and an unguarded loop abandons the remaining removals.

Step 2 - A tool that uses it

// src/tools/extentStats.js
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js";
import { HandleRegistry } from "../handleRegistry.js";

/**
 * Recompute summary statistics for the features currently on screen,
 * once per settled view movement.
 */
export function createExtentStats({ view, layer, onUpdate }) {
  const registry = new HandleRegistry();
  let abortController = null;

  async function recompute() {
    // Cancel any query still in flight - the user has moved on
    abortController?.abort();
    abortController = new AbortController();

    try {
      const layerView = await view.whenLayerView(layer);

      const stats = await layerView.queryFeatures(
        {
          geometry: view.extent,
          spatialRelationship: "intersects",
          outStatistics: [
            { statisticType: "count", onStatisticField: layer.objectIdField,
              outStatisticFieldName: "n" },
            { statisticType: "sum",   onStatisticField: "POPULATION",
              outStatisticFieldName: "total" },
            { statisticType: "avg",   onStatisticField: "POPULATION",
              outStatisticFieldName: "mean" },
          ],
        },
        { signal: abortController.signal }
      );

      onUpdate(stats.features[0]?.attributes ?? { n: 0, total: 0, mean: null });
    } catch (error) {
      if (error.name === "AbortError") return;   // expected; we cancelled it
      console.error("Extent statistics failed:", error);
      onUpdate(null);
    }
  }

  // Recompute when the view settles, not on every frame
  registry.add(
    reactiveUtils.watch(
      () => view.stationary,
      (stationary) => { if (stationary) recompute(); },
      { initial: true }
    ),
    "extentStats"
  );

  // Also recompute when the layer's filter changes
  registry.add(
    reactiveUtils.watch(() => layer.definitionExpression, recompute),
    "extentStats"
  );

  return {
    refresh: recompute,
    destroy() {
      abortController?.abort();
      registry.destroy();
    },
  };
}

The AbortController is as important as the handle cleanup. Pan quickly across a map and you fire five queries; four of their results are stale. Without cancellation you also pay for five round trips and get callbacks in non-deterministic order - the classic "the panel shows the wrong numbers occasionally" bug.

Step 3 - Debounced continuous feedback

Some things should update continuously - a coordinate readout, a hover highlight. Those need a different treatment:

// src/tools/coordinateReadout.js
import { HandleRegistry } from "../handleRegistry.js";
import { debounce } from "../spatial-toolkit.js";   // from Module 01

export function createCoordinateReadout({ view, element }) {
  const registry = new HandleRegistry();

  // Direct update - cheap, no network. Runs at pointer rate.
  const update = (event) => {
    const point = view.toMap({ x: event.x, y: event.y });
    if (!point) return;
    element.textContent =
      `${point.longitude.toFixed(5)}, ${point.latitude.toFixed(5)}`;
  };

  registry.add(view.on("pointer-move", update), "readout");
  registry.add(
    view.on("pointer-leave", () => { element.textContent = "-"; }),
    "readout"
  );

  return { destroy: () => registry.destroy() };
}

When to debounce and when not to:

Work Treatment
Update a text node Direct. It's a DOM write
Highlight a feature (hitTest) Throttle to ~30 ms - hitTest is async and does real work
Query a service view.stationary + abort
Update the URL Debounce 200 ms after stationary
Recompute a chart from loaded features stationary

Step 4 - Detect the leak

Prove to yourself that this matters.

// src/leakDemo.js

/** Deliberately leaks. Do not ship. */
export function leakyTool(view) {
  view.on("pointer-move", (e) => {
    // This closure captures `view`, and `bigArray` below.
    const bigArray = new Array(100_000).fill(Math.random());
    void bigArray;
  });
  // no handle, no cleanup
}

export function cleanTool(view) {
  const registry = new HandleRegistry();
  registry.add(view.on("pointer-move", () => {}), "clean");
  return { destroy: () => registry.destroy() };
}

The experiment:

  1. DevTools โ†’ Memory โ†’ take a heap snapshot
  2. Call leakyTool(view) 20 times, moving the mouse between calls
  3. Take another snapshot and compare - filter for Closure
  4. Repeat with cleanTool, calling destroy() each time
  5. Compare the deltas

You should see the leaky version accumulate. Seeing it once, in your own heap snapshot, is worth more than reading about it three times.


How it works

Why a handle keeps memory alive

view.on("pointer-move", handler);

The view stores handler in its listener list. handler is a closure over its defining scope

  • which includes any component state, refs, DOM nodes and data it referenced.

So the chain is:

view (long-lived)
  โ””โ”€ listener list
       โ””โ”€ handler closure
            โ””โ”€ everything the closure captured
                 โ””โ”€ โ€ฆ including, often, the view itself, and layers, and features

Nothing in that chain can be garbage collected while the view lives. And in a single-page app, the view often lives as long as the tab.

Why the SDK batches reactive callbacks

Setting view.center triggers a cascade: extent recomputes, scale recomputes, resolution recomputes, layer views re-query. If every watcher fired synchronously on each intermediate value, you'd see torn state and fire your callback four times for one logical change.

Batching to a microtask means all the derived properties settle, then watchers run once with consistent values. That is why sync: true exists but should be avoided.

Why whenLayerView can reject

try {
  const layerView = await view.whenLayerView(layer);
} catch (error) {
  // The layer failed to load, or was removed from the map before the
  // LayerView was created, or the view was destroyed.
}

A common cause in components: the component unmounts (view destroyed) while whenLayerView is pending. The rejection is correct behaviour, and an unhandled one shows up as Uncaught (in promise) with a stack that points nowhere useful.

Always try/catch around whenLayerView in code that can unmount.


Common mistakes

Not capturing the handle. view.on("click", handler); with no assignment is unremovable.

Reading a property outside the tracked getter. watch never fires.

Conditional reads in the getter. Only the branch that executed is tracked.

Watching view.extent for queries. Dozens of requests per pan. Use stationary.

No abort on in-flight queries. Stale results arrive out of order and overwrite fresh ones.

Adding handles after teardown. The async gap between await and add. Guard it.

Assuming handle.remove() can't throw. It can, after the target is destroyed. Wrap the teardown loop.

Unhandled whenLayerView rejection. Normal during unmount, noisy in the console.


Exercises

Exercise 18.1 - Instrument the registry

Add to HandleRegistry:

  1. A debug mode logging every add/remove with a stack trace
  2. A report() returning counts per group
  3. A development-only warning when size exceeds a threshold
  4. A Symbol.dispose implementation so using works (if your toolchain supports it)

Exercise 18.2 - The four watch mistakes

Write four watch calls that each demonstrate one failure mode, then fix each:

  1. A getter that reads outside the tracking context
  2. A conditional read
  3. A watch that fires too often
  4. A watch that mutates the property it watches (infinite loop - cap it with a counter)

Document each with a comment explaining the symptom.

Exercise 18.3 - Extent-driven dashboard

Build a panel that, for the current extent, shows:

  • Feature count
  • Sum and mean of a numeric field
  • The top 5 values of a categorical field
  • A loading indicator driven by view.updating

Requirements: aborts stale queries, updates only on stationary, and handles the empty-extent case (zero features) without showing NaN.

Exercise 18.4 - Leak, measured

Do the heap snapshot experiment from Step 4 and record:

  • Bytes retained per leaked handler
  • What the retainer chain looks like in DevTools
  • What happens after 100 iterations

Write it up in five sentences. This is the argument you'll make to a colleague who thinks cleanup is optional.


Checkpoint

  1. What do view.on() and reactiveUtils.watch() have in common?
  2. Why must the property be read inside the watch getter?
  3. What's wrong with watch(() => view.extent, runQuery)?
  4. Why can handle.remove() throw, and what should you do about it?
  5. Why does adding a handle after teardown happen at all?
  6. What does view.updating tell you that view.stationary doesn't?
  7. Name the retainer chain that makes a forgotten listener a memory leak.
  1. Both return a handle with .remove(), and both leak if you don't call it.
  2. Dependency tracking works by observing which Accessor properties are read during the getter's execution. A value read outside has no tracked dependency.
  3. extent changes on every animation frame during a pan, so it fires dozens of times per interaction. Use view.stationary.
  4. The handle's target may already be destroyed (e.g. view.destroy() ran first). Wrap each removal in try/catch so one failure doesn't abandon the rest of the teardown.
  5. An async setup - await view.whenLayerView(...) - can resolve after the component that started it has unmounted. Guard with a destroyed flag and remove immediately.
  6. updating is true while anything is loading (tiles, features, layers); stationary is about camera movement only. A view can be stationary and still updating.
  7. view โ†’ listener list โ†’ handler closure โ†’ captured scope (component state, refs, data) โ†’ often back to the view and its layers. None of it can be collected.

Further reading


Next: Module 19 - hitTest and Highlight