Module 37 - React Integration Patterns

Level 8 ยท Professional Practice ยท ๐Ÿ”ด ยท 5 hours ยท Prereq: Module 36


What you'll build

A React map application with no leaks, no double-mounts, no stale closures, and no re-render storms - plus the useTool hook pattern that every tool in this repository is built on.


Why this matters

React and the ArcGIS SDK have opposite models. React is declarative, re-runs your function freely, and owns the DOM. The SDK is imperative, holds long-lived stateful objects, and owns a canvas.

Bridging them badly produces four specific bugs, all of which look like something else. This module is about the four.


Concepts

1. The four bugs

Symptom Cause
Two maps render, or the map goes black after a hot reload The mount effect ran twice (StrictMode) and cleanup didn't destroy the view
An event handler sees old state Stale closure - the handler captured an earlier render's variables
Memory grows on every route change Handles and views not destroyed
The map re-initialises constantly A dependency in the mount effect changes identity every render

All four come from one root: the SDK's objects live longer than a React render, and React gives you no lifetime that matches.

2. The container ref and the view ref

import { useEffect, useRef, useState } from "react";

export function MapView({ itemId }) {
  const containerRef = useRef(null);     // the DOM node - React owns it
  const viewRef = useRef(null);          // the SDK view - we own it
  const [ready, setReady] = useState(false);

  useEffect(() => {
    // React 18+ StrictMode runs effects twice in development. This flag lets
    // the cleanup tell an in-flight async setup that it's been superseded.
    let cancelled = false;

    async function initialise() {
      const [{ default: WebMap }, { default: MapView }] = await Promise.all([
        import("@arcgis/core/WebMap.js"),
        import("@arcgis/core/views/MapView.js"),
      ]);

      if (cancelled) return;             // unmounted during the import

      const view = new MapView({
        container: containerRef.current,
        map: new WebMap({ portalItem: { id: itemId } }),
      });

      viewRef.current = view;
      await view.when();

      if (cancelled) {                   // unmounted during initialisation
        view.destroy();
        viewRef.current = null;
        return;
      }

      setReady(true);
    }

    initialise();

    return () => {
      cancelled = true;
      viewRef.current?.destroy();        // releases the WebGL context
      viewRef.current = null;
      setReady(false);
    };
  }, [itemId]);

  return <div ref={containerRef} style={{ position: "absolute", inset: 0 }} />;
}

The cancelled flag is not optional. Between await import(...) and view.when() there are two points where the component can unmount. Without the flag you create a view into a detached DOM node and leak a WebGL context.

Browsers limit concurrent WebGL contexts (typically 8-16). Leak enough and the browser silently drops the oldest - which is why the symptom is "the map goes black after a few hot reloads" rather than an error.

3. Stale closures and the ref mirror

// โŒ The handler captures THIS render's `selectedId`. Forever.
const [selectedId, setSelectedId] = useState(null);

useEffect(() => {
  const handle = view.on("click", () => {
    console.log(selectedId);      // always null
  });
  return () => handle.remove();
}, []);                            // empty deps: registered once

Two fixes, and they're for different situations:

// Fix A - mirror to a ref. Use when the handler must be long-lived.
const selectedIdRef = useRef(selectedId);
useEffect(() => { selectedIdRef.current = selectedId; }, [selectedId]);

useEffect(() => {
  const handle = view.on("click", () => {
    console.log(selectedIdRef.current);   // current value
  });
  return () => handle.remove();
}, []);
// Fix B - re-register on change. Use when re-registering is cheap and the
// handler genuinely depends on the value.
useEffect(() => {
  const handle = view.on("click", () => console.log(selectedId));
  return () => handle.remove();
}, [selectedId]);

Prefer A for SDK handlers. Re-registering a pointer-move handler on every state change is wasteful, and SDK subscriptions have setup cost. Prefer B for cheap handlers with few dependencies.

This repository uses A throughout: editHeightRef, activeToolRef, shapesRef, selectedIdRef in DesignToolbar.jsx, with a documented rule requiring it.

A reusable helper:

// src/hooks/useLatest.js
import { useRef, useEffect } from "react";

/** A ref that always holds the latest value. For reading state inside long-lived callbacks. */
export function useLatest(value) {
  const ref = useRef(value);
  useEffect(() => { ref.current = value; }, [value]);
  return ref;
}

4. The handle registry as a hook

// src/hooks/useHandles.js
import { useEffect, useRef } from "react";
import { HandleRegistry } from "../handleRegistry.js";   // Module 18

/**
 * A HandleRegistry scoped to the component's lifetime.
 * Everything added is removed on unmount, including handles added
 * after an await that resolved post-unmount.
 */
export function useHandles() {
  const registryRef = useRef(null);
  registryRef.current ??= new HandleRegistry();

  useEffect(() => {
    const registry = registryRef.current;
    return () => registry.destroy();
  }, []);

  return registryRef.current;
}
function MyTool({ view }) {
  const handles = useHandles();

  useEffect(() => {
    if (!view) return;
    handles.add(view.on("click", onClick), "myTool");
    handles.add(reactiveUtils.watch(() => view.zoom, onZoom), "myTool");
    return () => handles.removeGroup("myTool");
  }, [view, handles]);
}

The registry's destroyed-guard (Module 18) matters most here. An await view.whenLayerView() that resolves after unmount would otherwise add an unremovable handle.

5. useEffect dependency identity

// โŒ `config` is a new object every render, so the effect re-runs every render,
//    destroying and rebuilding the view continuously.
function Map({ itemId }) {
  const config = { basemap: "arcgis/navigation", zoom: 12 };
  useEffect(() => { /* build view */ }, [itemId, config]);
}
// โœ… Depend on primitives, or memoise
const config = useMemo(
  () => ({ basemap, zoom }),
  [basemap, zoom]
);
useEffect(() => { /* โ€ฆ */ }, [itemId, config]);

// โœ… Better: destructure to primitives
useEffect(() => { /* โ€ฆ */ }, [itemId, basemap, zoom]);

Rule: an effect that builds a view should depend on primitives only. Objects, arrays and inline functions all break referential equality and cause rebuilds.

6. What belongs in React state and what doesn't

Put in React state Keep in a ref / the SDK
Which tool is active The view
Panel open/closed Layers
Form values Graphics
Query results you render LayerViews
Loading/error flags Widget instances
User preferences Event handles

The rule: if rendering depends on it, it's state. If only the SDK needs it, it's a ref.

Putting the view in state causes a re-render every time you touch it. Putting the active tool in a ref means the toolbar doesn't highlight.

7. The useTool pattern

Every analysis tool follows one shape:

// src/hooks/useViewshed.js
import { useCallback, useEffect, useRef, useState } from "react";
import { useHandles } from "./useHandles.js";
import { useLatest } from "./useLatest.js";

/**
 * Owns all viewshed state, refs and ArcGIS lifecycle.
 *
 * The panel component renders it and holds none of it. This is the seam a
 * project save/restore hangs off - the whole tool's state is `config` plus
 * what it put in the scene, both already plain JSON.
 */
export function useViewshed({ view, activeAnalysis, onActiveAnalysisChange }) {
  const handles = useHandles();

  const [config, setConfig] = useState({
    farDistance: 1000,
    horizontalFieldOfView: 120,
    verticalFieldOfView: 60,
    observerHeight: 1.7,
  });
  const [count, setCount] = useState(0);
  const [placing, setPlacing] = useState(false);

  const analysisRef = useRef(null);
  const configRef = useLatest(config);          // read inside the click handler
  const isActive = activeAnalysis === "viewshed";

  // โ”€โ”€ Create the analysis when the tool becomes active โ”€โ”€
  useEffect(() => {
    if (!view || !isActive) return;

    let cancelled = false;

    (async () => {
      const { default: ViewshedAnalysis } =
        await import("@arcgis/core/analysis/ViewshedAnalysis.js");
      if (cancelled) return;

      const analysis = new ViewshedAnalysis({ viewsheds: [] });
      view.analyses.add(analysis);
      analysisRef.current = analysis;

      const analysisView = await view.whenAnalysisView(analysis);
      if (cancelled) { view.analyses.remove(analysis); return; }
      analysisView.interactive = true;
    })();

    return () => {
      cancelled = true;
      if (analysisRef.current) {
        view.analyses.remove(analysisRef.current);
        analysisRef.current = null;
      }
      setCount(0);
      setPlacing(false);
    };
  }, [view, isActive]);

  // โ”€โ”€ Click to place โ”€โ”€
  useEffect(() => {
    if (!view || !isActive || !placing) return;

    handles.add(view.on("click", async (event) => {
      event.stopPropagation();

      const { default: Viewshed } = await import("@arcgis/core/analysis/Viewshed.js");
      const current = configRef.current;        // NOT the captured `config`

      let z = current.observerHeight;
      try {
        const { geometry } = await view.map.ground.queryElevation(event.mapPoint);
        z = (geometry.z ?? 0) + current.observerHeight;
      } catch { /* no elevation data - use the raw height */ }

      analysisRef.current?.viewsheds.add(new Viewshed({
        observer: { longitude: event.mapPoint.longitude,
                    latitude: event.mapPoint.latitude, z,
                    spatialReference: event.mapPoint.spatialReference },
        farDistance: current.farDistance,
        horizontalFieldOfView: current.horizontalFieldOfView,
        verticalFieldOfView: current.verticalFieldOfView,
        tilt: 90,
      }));

      setCount(analysisRef.current?.viewsheds.length ?? 0);
    }), "viewshed-place");

    return () => handles.removeGroup("viewshed-place");
  }, [view, isActive, placing, handles, configRef]);

  // โ”€โ”€ Live config updates apply to existing viewsheds โ”€โ”€
  useEffect(() => {
    analysisRef.current?.viewsheds.forEach((viewshed) => {
      viewshed.farDistance = config.farDistance;
      viewshed.horizontalFieldOfView = config.horizontalFieldOfView;
      viewshed.verticalFieldOfView = config.verticalFieldOfView;
    });
  }, [config]);

  const reset = useCallback(() => {
    analysisRef.current?.viewsheds.removeAll();
    setCount(0);
    setPlacing(false);
  }, []);

  const activate = useCallback(() => {
    onActiveAnalysisChange("viewshed");
    setPlacing(true);
  }, [onActiveAnalysisChange]);

  return {
    // state for the panel
    config, count, placing, isActive,
    // actions
    setConfig, setPlacing, activate, reset,
    // for the ESC registry
    serialize: useCallback(() => ({
      config,
      viewsheds: analysisRef.current?.viewsheds.toArray().map((v) => v.toJSON()) ?? [],
    }), [config]),
  };
}
// Sidebar.jsx - composes tools and holds none of their state
function Sidebar({ view, theme }) {
  const [activeAnalysis, setActiveAnalysis] = useState(null);

  const viewshed = useViewshed({ view, activeAnalysis, onActiveAnalysisChange: setActiveAnalysis });
  const slice = useSlice({ view, activeAnalysis, onActiveAnalysisChange: setActiveAnalysis });
  const shadow = useShadowCast({ view, activeAnalysis, onActiveAnalysisChange: setActiveAnalysis });

  // ESC is registry-driven: a new tool joins by adding its reset here
  const toolResets = useMemo(
    () => ({ viewshed: viewshed.reset, slice: slice.reset, shadowCast: shadow.reset }),
    [viewshed.reset, slice.reset, shadow.reset]
  );

  useEffect(() => {
    const onKeyDown = (event) => {
      if (event.key !== "Escape") return;
      toolResets[activeAnalysis]?.();
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [activeAnalysis, toolResets]);

  return (
    <aside>
      <ToolButtons active={activeAnalysis} onSelect={setActiveAnalysis} />
      {activeAnalysis === "viewshed" && <ViewshedPanel theme={theme} {...viewshed} />}
      {activeAnalysis === "slice"    && <SlicePanel theme={theme} {...slice} />}
      {activeAnalysis === "shadowCast" && <ShadowCastPanel theme={theme} {...shadow} />}
    </aside>
  );
}

This is the architecture this repository uses, and its CLAUDE.md records the payoff: "Sidebar.jsx was 3,620 lines with every tool's state inline before this split; it is 624 now." Plus the rule: don't move tool state back into Sidebar.jsx.

8. Panel persistence

Unmounting a panel destroys its state. Sometimes that's right; often it isn't.

// โŒ Every close/open loses scroll position, form input, expanded sections
{filterOpen && <FilterPanel />}

// โœ… Mount once, hide with CSS
const [everOpened, setEverOpened] = useState(false);
useEffect(() => { if (filterOpen) setEverOpened(true); }, [filterOpen]);

{everOpened && (
  <div style={{ display: filterOpen ? "block" : "none" }}>
    <FilterPanel />
  </div>
)}

The everOpened guard means a user who never opens the panel never pays for it - you get lazy construction and state persistence.

This repository documents the pattern as filterEverOpened / analysisEverOpened.

9. Rendering widgets into React DOM

function LegendPanel({ view }) {
  const containerRef = useRef(null);
  const widgetRef = useRef(null);

  useEffect(() => {
    if (!view || !containerRef.current) return;

    let cancelled = false;

    (async () => {
      const { default: Legend } = await import("@arcgis/core/widgets/Legend.js");
      if (cancelled || !containerRef.current) return;

      // The container must be IN THE DOM at construction time. It is here,
      // because effects run after commit - but not if we constructed at
      // module scope or in the render body.
      widgetRef.current = new Legend({ view, container: containerRef.current });
    })();

    return () => {
      cancelled = true;
      widgetRef.current?.destroy();
      widgetRef.current = null;
    };
  }, [view]);

  return <div ref={containerRef} className="legend-panel" />;
}

Never render children into a div an SDK widget owns. React will try to reconcile DOM the widget mutates, and you get NotFoundError: The node to be removed is not a child of this node.

10. Map components in JSX

import "@arcgis/map-components/components/arcgis-scene";
import "@arcgis/map-components/components/arcgis-zoom";

function Scene({ itemId, onViewReady }) {
  const sceneRef = useRef(null);

  useEffect(() => {
    const element = sceneRef.current;
    if (!element) return;

    const onReady = () => onViewReady(element.view);
    element.addEventListener("arcgisViewReadyChange", onReady);
    return () => element.removeEventListener("arcgisViewReadyChange", onReady);
  }, [onViewReady]);

  return (
    <arcgis-scene ref={sceneRef} item-id={itemId} style={{ height: "100%" }}>
      <arcgis-zoom position="top-left" />
    </arcgis-scene>
  );
}

React 19 sets non-string props as properties on custom elements automatically, so center={[lon, lat]} works. In React 18 and earlier you needed ref.current.center = [...] in an effect.

onViewReady must be stable - wrap it in useCallback in the parent, or the effect re-registers every render.


Build it - the application shell

Step 1 - The view provider

// src/map/ViewProvider.jsx
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";

const ViewContext = createContext(null);

export function useMapView() {
  const context = useContext(ViewContext);
  if (context === undefined) throw new Error("useMapView must be used inside <ViewProvider>");
  return context;
}

export function ViewProvider({ itemId, viewType = "3d", children }) {
  const containerRef = useRef(null);
  const viewRef = useRef(null);
  const [view, setView] = useState(null);
  const [status, setStatus] = useState({ state: "loading", error: null });

  useEffect(() => {
    let cancelled = false;

    async function initialise() {
      setStatus({ state: "loading", error: null });

      try {
        const [{ default: MapClass }, { default: ViewClass }] = await Promise.all([
          viewType === "3d"
            ? import("@arcgis/core/WebScene.js")
            : import("@arcgis/core/WebMap.js"),
          viewType === "3d"
            ? import("@arcgis/core/views/SceneView.js")
            : import("@arcgis/core/views/MapView.js"),
        ]);

        if (cancelled) return;

        const instance = new ViewClass({
          container: containerRef.current,
          map: new MapClass({ portalItem: { id: itemId } }),
        });

        viewRef.current = instance;
        await instance.when();

        if (cancelled) { instance.destroy(); viewRef.current = null; return; }

        setView(instance);
        setStatus({ state: "ready", error: null });
      } catch (error) {
        if (cancelled) return;
        setStatus({ state: "error", error });
      }
    }

    initialise();

    return () => {
      cancelled = true;
      // destroy() releases the WebGL context. Browsers cap concurrent
      // contexts at ~8-16; leaking them makes the map go black with no error.
      viewRef.current?.destroy();
      viewRef.current = null;
      setView(null);
    };
    // Primitives only - an object here would rebuild the view every render.
  }, [itemId, viewType]);

  // Memoise the context value or every consumer re-renders on any parent render
  const value = useMemo(() => ({ view, status }), [view, status]);

  return (
    <ViewContext.Provider value={value}>
      <div ref={containerRef} className="view-container" />
      {status.state === "error" && <ViewError error={status.error} />}
      {children}
    </ViewContext.Provider>
  );
}

useMemo on the context value is the difference between "the panel re-renders when the sidebar opens" and "every consumer of the context re-renders on every parent render."

Step 2 - The layer view hook

// src/hooks/useLayerView.js
import { useEffect, useState } from "react";

/**
 * The LayerView for a layer in a view, with the unmount race handled.
 *
 * `whenLayerView` rejects if the view is destroyed while it's pending - a
 * normal occurrence during navigation, and an unhandled rejection otherwise.
 */
export function useLayerView(view, layer) {
  const [layerView, setLayerView] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    if (!view || !layer) { setLayerView(null); return; }

    let cancelled = false;
    setLayerView(null);
    setError(null);

    view.whenLayerView(layer)
      .then((lv) => { if (!cancelled) setLayerView(lv); })
      .catch((err) => {
        if (cancelled) return;      // expected: the view was destroyed
        setError(err);
      });

    return () => { cancelled = true; };
  }, [view, layer]);

  return { layerView, error };
}

Step 3 - A filter hook with restore-on-unmount

// src/hooks/useLayerFilter.js
import { useEffect, useRef } from "react";

/**
 * Apply a client-side filter, restoring the original on unmount.
 *
 * `layerView.filter` lives on the SDK object, outside React's lifecycle.
 * Without the restore, closing this panel leaves the map filtered - the
 * same class of bug as `definitionExpression` (Module 21).
 */
export function useLayerFilter(layerView, where) {
  const originalRef = useRef(undefined);

  useEffect(() => {
    if (!layerView) return;

    // Capture the pre-existing filter once, on first application
    if (originalRef.current === undefined) {
      originalRef.current = layerView.filter ?? null;
    }

    layerView.filter = where ? { where } : originalRef.current;

    return () => {
      // Only restore if the layerView is still alive - it may have been
      // destroyed with the view.
      if (layerView.destroyed) return;
      layerView.filter = originalRef.current ?? null;
    };
  }, [layerView, where]);
}

The layerView.destroyed check prevents a throw during unmount when the view was destroyed first - a common ordering when a route changes.

Step 4 - Error boundary

// src/map/MapErrorBoundary.jsx
import { Component } from "react";

/**
 * An SDK error inside a render can blank the whole app. This contains it and
 * gives the user a path back.
 */
export class MapErrorBoundary extends Component {
  state = { error: null };

  static getDerivedStateFromError(error) { return { error }; }

  componentDidCatch(error, info) {
    // Report to your monitoring, with enough context to be actionable
    console.error("Map error:", error, info.componentStack);
    this.props.onError?.(error, info);
  }

  render() {
    if (!this.state.error) return this.props.children;

    return (
      <div className="map-error" role="alert">
        <h2>The map couldn't be displayed</h2>
        <p>{describeError(this.state.error)}</p>
        <button type="button" onClick={() => this.setState({ error: null })}>
          Try again
        </button>
      </div>
    );
  }
}

function describeError(error) {
  const message = error?.message ?? String(error);
  if (/webgl/i.test(message)) {
    return "Your browser or graphics driver doesn't support the 3D rendering this map needs. " +
           "Try a different browser, or update your graphics driver.";
  }
  if (/403|permission/i.test(message)) {
    return "You don't have access to this map. Sign in with an account that does.";
  }
  if (/network|failed to fetch/i.test(message)) {
    return "Couldn't reach the map service. Check your connection and try again.";
  }
  return message;
}

Step 5 - Route-level code splitting

// src/routes/pages.jsx
import { lazy } from "react";

// Every page is lazy. One static import of the viewer drags the entire
// ArcGIS chain into the entry chunk - for every route, including a
// marketing homepage that renders no map.
export const HomePage    = lazy(() => import("../pages/HomePage.jsx"));
export const ViewerPage  = lazy(() => import("../pages/viewer/App.jsx"));
export const AdminPage   = lazy(() => import("../pages/admin/Dashboard.jsx"));
export const SupportPage = lazy(() => import("../pages/SupportPage.jsx"));
// src/routes/router.jsx
import { Suspense } from "react";
import { createBrowserRouter } from "react-router-dom";
import * as pages from "./pages.jsx";

const withSuspense = (Component) => (
  <Suspense fallback={<PageSkeleton />}>
    <Component />
  </Suspense>
);

export const router = createBrowserRouter([
  { path: "/",        element: withSuspense(pages.HomePage) },
  { path: "/viewer",  element: withSuspense(pages.ViewerPage) },
  { path: "/admin/*", element: withSuspense(pages.AdminPage) },
  { path: "/support", element: withSuspense(pages.SupportPage) },
]);

pages.jsx exists separately so router.jsx can export the non-component router without tripping react-refresh/only-export-components. This repository documents the measured effect of the split: 59 files / 1.46 MB โ†’ 20 files / 0.70 MB on initial load.

Never add a static import of a page component into router.jsx. It defeats the entire split, silently.


How it works

Why StrictMode double-invokes effects

React 18's StrictMode mounts, unmounts and remounts every component in development, to surface components that aren't resilient to being mounted twice - which is what Suspense and future concurrent features require.

It is not a bug and you should not disable it. A component that breaks under StrictMode has a real cleanup defect that will bite in production during a route change or a Suspense retry.

Why view.destroy() matters more than other cleanup

destroy() releases:

  • The WebGL context (browsers cap these at ~8-16)
  • Every LayerView and its GPU buffers
  • Internal event handles
  • Web workers
  • The ResizeObserver on the container

Leaking a view leaks all of it. The WebGL context is the one with a hard cap, which is why the symptom is "the map stops working after N navigations" rather than gradual slowdown.

Why the ref mirror works

useRef returns the same object on every render. Mutating ref.current doesn't trigger a re-render, and a closure that captured the ref object reads whatever is in it at call time.

That's precisely the escape hatch needed for a callback that outlives the render that created it.

Why context values must be memoised

<Context.Provider value={{ view, status }}> creates a new object every render. Every consumer re-renders because the value's identity changed, even when view and status are unchanged.

With a map application, "every consumer re-renders" can mean every panel, every tool, and every list - on every parent render.

Why panels should persist

Unmounting destroys component state and any SDK objects the component owned. Reopening rebuilds them, which for a widget means a fresh construction and a fresh set of network requests.

Hiding with CSS keeps both. The cost is the memory of a hidden subtree, which is small compared to a rebuilt widget.


Common mistakes

No cancelled flag around async setup. Views created into detached nodes; leaked WebGL contexts.

Reading state in an SDK handler with empty deps. Stale closure.

Objects or inline functions in a mount effect's deps. The view rebuilds every render.

Putting the view in React state. A re-render every time you touch it.

Not memoising a context value. Every consumer re-renders on every parent render.

Rendering React children into a widget's container. NotFoundError during reconciliation.

Disabling StrictMode to make a bug go away. The bug is real; StrictMode just found it.

A static page import in router.jsx. Silently defeats route splitting.

Not restoring layerView.filter on unmount. The map stays filtered after the panel closes.

Tool state in the composing component. The 3,620-line component.


Exercises

Exercise 37.1 - Prove the leak

  1. Build a component that creates a SceneView with no cleanup
  2. Mount and unmount it 20 times via a route toggle
  3. Watch WEBGL_lose_context warnings appear, or count contexts in a heap snapshot
  4. Add cleanup and verify the count stays at 1
  5. Record how many navigations it took before the map went black

Exercise 37.2 - The stale closure

Build a tool whose click handler reads activeTool from state with empty deps.

  1. Verify it always sees the initial value
  2. Fix it with useLatest
  3. Fix it again by re-registering on change
  4. Measure the difference in handler registrations over 100 tool switches
  5. Write the guidance you'd give a team

Exercise 37.3 - Convert a tool

Take any tool from Module 33 or 34 and convert it to the useTool pattern:

  • All state in the hook
  • The panel component renders and holds nothing
  • reset exposed for the ESC registry
  • serialize/restore for save/load
  • Full cleanup verified under StrictMode

Exercise 37.4 - Measure the split

In a React app with a map route and a non-map route:

  1. Static-import the map page in the router; build and record the entry chunk size
  2. Convert to lazy + Suspense; rebuild and record
  3. Load the non-map route and record what's actually downloaded
  4. Present the before/after as a table

Checkpoint

  1. Why does React StrictMode run your mount effect twice, and what should you do about it?
  2. What does view.destroy() release that makes leaking it worse than a normal leak?
  3. What is a stale closure and what are the two fixes?
  4. Why must a context value be memoised?
  5. What belongs in React state and what belongs in a ref?
  6. Why keep tool state in a hook rather than the composing component?
  7. Why does one static page import in router.jsx defeat code splitting?
  1. To surface components that aren't resilient to being mounted twice - a requirement for Suspense and concurrent rendering. Fix the cleanup; don't disable StrictMode.
  2. The WebGL context, which browsers cap at roughly 8-16 concurrently. Exceeding the cap makes the browser silently drop the oldest, so the symptom is a black map rather than an error.
  3. A callback capturing an earlier render's variables and reading them forever. Fix A: mirror the value into a ref the callback reads at call time. Fix B: re-register the callback when the value changes.
  4. Without it the provider creates a new object every render, so every consumer re-renders on every parent render regardless of whether the contained values changed.
  5. React state: anything rendering depends on (active tool, panel open, form values, results). Refs: SDK objects and anything only the SDK needs (view, layers, widgets, handles).
  6. It keeps the composing component small, makes each tool independently testable, and gives you a natural serialisation seam - the tool's whole state is its config plus what it put in the scene.
  7. lazy() only splits what isn't statically reachable from the entry module. One static import makes the page - and its entire ArcGIS dependency tree - part of the entry chunk for every route.

Further reading


Next: Module 38 - Application Architecture