AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Docs: Preserving UI State Guide Missing Warning For Imperative DOM/WebGL Libraries (Mapbox GL, Three.Js, Etc.)

Next.js documentation's Preserving UI State guide lacks a warning about imperative DOM/WebGL libraries like Mapbox GL and Three.js, which destroy internal DOM references during effect cleanup. When routes reappear, effects re-run but the library instance is already destroyed, causing a TypeError only in production builds. The fix is to remount the library from scratch instead of reusing stale instances.

highConfidence 90%Next.jsAffected VNext.js 16.xAffected Vreact-Map-Gl 8.xAffected Vmapbox-Gl 3.x

Origin Analysis

The guide only covers timers and media elements, omitting libraries that internally manage DOM nodes and destroy them in cleanup. When Next.js re-runs effects on route activation, the library instance is reused despite being in a destroyed state, leading to 'appendChild' on undefined. This is exacerbated by dev/prod build differences (Turbopack vs Webpack) which mask the issue during development.
1. Create a Next.js 16 app with react-map-gl v8 and Mapbox GL JS v3. 2. In a client component, initialize Mapbox GL in useEffect and call map.remove() in cleanup. 3. Use the component within a route that is preserved via cacheComponents or similar. 4. Navigate away and back to the route in production build (next build && next start). 5. Observe TypeError: Cannot read properties of undefined (reading 'appendChild') at Marker.addTo.

Fixing Code Block

Edge Case Audit

Using a key causes the component to lose all internal state (map position, markers, etc.) on route change, which may degrade user experience if state preservation is expected. Frequent remounts can incur performance overhead for complex maps. If Mapbox GL or react-map-gl updates change destroy behavior, this workaround may need adjustment. Rollback: revert to useEffect-based cleanup but modify cleanup to remove the container DOM element entirely and recreate it on each mount, or explore library-specific methods to properly destroy and recreate without key remount.

Ecosystem Topology