I make Last Thaw, a free browser strategy game. Up to a hundred players start with five settlers on a real map of Earth, cut into 408 regions, and have 30 real days to build an empire while an ice age advances from both poles. It's in early access and I'm looking for people to test it.
Most matches are played on Earth, but a match can also be played on Pangaea, the supercontinent of 250 million years ago (the about page has the details). Last week the replay of a finished Pangaea match crashed with this on the error screen:
map pangaea is not loaded Live Pangaea matches worked. Replays of Earth matches worked. Only the replay of a Pangaea match fell over, and only on a cold load. The cause was four lines of React I'd have sworn were fine: a piece of state that answered a question about one prop value and kept answering it after the prop changed.
How maps get loaded
Earth ships in the main bundle because the home page and the lobby draw it. Pangaea doesn't. Its regions, coast points and sea lanes are a few hundred kilobytes of JSON that most visitors never need, so the web app fetches them the first time a match on that map opens.
The shared package keeps a small registry of the maps that have arrived:
const registry = new Map<MapId, MapData>(); /** Earth is registered at load; other maps when their JSON arrives. */ export function registerWorld(id: MapId, w: WorldMap): void { registry.set(id, { id, world: w, byId: new Map(w.regions.map((r) => [r.id, r] as const)) }); } registerWorld("earth", earthJson as WorldMap); export function isMapLoaded(id: MapId): boolean { return registry.has(id); } Every helper that needs geography (neighbors, distances, which regions the ice has reached) reads the map through one function, and that function is strict on purpose:
function data(): MapData { const id = resolver(); // which map is in play right now const d = registry.get(id); if (!d) throw new Error(`map ${id} is not loaded`); return d; } I'd rather it throw than quietly fall back to Earth. A Pangaea match drawn with Earth's regions would be a much stranger bug to chase than an error with the map's name in it.
On the web side, a component called MapScope puts a map in scope for everything inside it and holds the children back until the map is there:
<MapScope map={data?.match.map ?? "earth"} fallback={<p>Loading the map...</p>}> <WorldMap ... /> </MapScope> That ?? "earth" is the replay page being reasonable. It doesn't know which map the match used until the replay data arrives, so it starts on Earth.
The bug
Here's MapScope as it was:
export function MapScope({ map, children, fallback = null }) { // true straight away if the map is already loaded const [ready, setReady] = useState(isMapLoaded(map) && !!assets[map]); useEffect(() => { let live = true; if (isMapLoaded(map) && assets[map]) setReady(true); else { setReady(false); void ensureMap(map).then(() => live && setReady(true)); } return () => { live = false; }; }, [map]); if (!ready) return <>{fallback}</>; current = map; // everything below now reads this map return <>{children}</>; } Read it top to bottom and it looks right. If the map is loaded, ready. If not, not ready, fetch it, then ready. The effect reruns when map changes.
Now walk through the replay page on a cold load:
- The page mounts. The replay hasn't arrived, so
mapis"earth". Earth is in the bundle, soreadystarts outtrue. - The replay arrives. The match was on Pangaea, so the page renders again with
map="pangaea". - During that render,
readyis stilltrue. It was computed for Earth.useStateonly uses its initial value once, and the effect that would set it tofalsehasn't run yet, because effects run after the render. - So
MapScopesets the current map to Pangaea and renders the children. The map component asks for the active world, the registry has no Pangaea, anddata()throws.
The effect would have fixed everything a moment later. It never got the chance. The render that needed the right answer came first, and the error boundary took over the page.
Live matches never hit this because the match page knows its map before it mounts MapScope, so the prop never changes underneath it. The replay page is the only place where the same mounted MapScope sees two different maps.
The fix
The mistake wasn't the effect or the fetch. It was keeping ready at all. "Is this map loaded?" already has an owner, the registry, and the registry answers for whichever map you ask about. My ready flag was a copy of that answer for whatever map happened to be in the prop when it was last set.
So the copy went away. The component asks the registry on every render, and the only state left is a counter that exists to cause a render when a fetch lands:
export function MapScope({ map, children, fallback = null }) { // Only a signal to draw again once a fetch lands. const [, setLoadedTick] = useState(0); useEffect(() => { let live = true; if (!(isMapLoaded(map) && assets[map])) { void ensureMap(map).then(() => live && setLoadedTick((n) => n + 1)); } return () => { live = false; }; }, [map]); // Asked fresh every render, for the map in the prop right now. if (!(isMapLoaded(map) && assets[map])) return <>{fallback}</>; current = map; return <>{children}</>; } Same number of lines, give or take. The difference is that there's no moment where the component can believe something about a map it's no longer showing.
You could also fix this by putting key={map} on the component so React throws the old instance away when the map changes. That works, but it fixes the symptom at the call site, and the next page that uses MapScope has to remember to do it too. I'd rather the component be right no matter how it's called.
The test
The reason this got to production is that it needs a specific order of arrival: the page first, the replay second, the map files third. On my machine everything comes back so fast that the window barely exists. So the test builds the window on purpose, with Playwright holding each response back:
await page.route("**/api/matches/*/replay", async (route) => { // Late enough that the page has already drawn Earth. await new Promise((r) => setTimeout(r, 400)); await route.fulfill({ contentType: "application/json", body: JSON.stringify(pangaeaReplay) }); }); // The map's own files arrive later still, so there is a moment // when the match is known and its map is not. await page.route("**/map/pangaea/world.json", async (route) => { await new Promise((r) => setTimeout(r, 600)); await route.continue(); }); await page.goto("/match/grey-snowfall/replay"); await expect(page.getByText("Loading the map...")).toBeVisible(); await expect(page.getByText("Loading the map...")).toHaveCount(0); await expect(page.getByText("Something went wrong on this page")).toHaveCount(0); It checks both halves: the loading line shows while the map is on its way, and it goes away without the error screen taking its place. Against the old component this test fails every time, which is what I want from a test for a timing bug.
What I took from it
- If a
useStateinitial value is computed from a prop, ask what happens when that prop changes. The initial value won't be computed again, and an effect that corrects it runs one render too late. - If the truth already lives somewhere you can read synchronously, read it during render. Keep state only for the thing React can't know by itself, here that a fetch finished.
- Timing bugs hide on a fast connection. Slow the responses down in a test and put them in the order that hurts.
If you want to see the map this is all for, a finished match's replay plays the whole 30 days back in about a minute. You can find them from lastthaw.com, and the game is free to play in the browser. Feel free to borrow the delayed-route trick for your own loading states.