diff --git a/.changeset/unmount-root-on-map-remove.md b/.changeset/unmount-root-on-map-remove.md new file mode 100644 index 0000000..4bf77df --- /dev/null +++ b/.changeset/unmount-root-on-map-remove.md @@ -0,0 +1,5 @@ +--- +"react-three-map": patch +--- + +Unmount the `` root when the map is removed, so it no longer leaks after the whole map unmounts. diff --git a/src/core/canvas-in-layer/use-canvas-in-layer.tsx b/src/core/canvas-in-layer/use-canvas-in-layer.tsx index 955e571..e5420a1 100644 --- a/src/core/canvas-in-layer/use-canvas-in-layer.tsx +++ b/src/core/canvas-in-layer/use-canvas-in-layer.tsx @@ -13,13 +13,14 @@ export function useCanvasInLayer(props: CanvasProps,fromLngLat: FromLngLat, map: latitude, longitude, altitude, fromLngLat, }); - const { onRemove, useThree, r3m } = useRoot(fromLngLat, map, props); + const { onAdd, onRemove, useThree, r3m } = useRoot(fromLngLat, map, props); const render = useRender({origin, frameloop, useThree, map, r3m}); return { id: props.id, beforeId: props.beforeId, + onAdd, onRemove, render, type: 'custom', diff --git a/src/core/canvas-in-layer/use-root.tsx b/src/core/canvas-in-layer/use-root.tsx index 0ec342a..9e2d262 100644 --- a/src/core/canvas-in-layer/use-root.tsx +++ b/src/core/canvas-in-layer/use-root.tsx @@ -80,7 +80,13 @@ export function useRoot( }) + // map.remove() does not call the layer onRemove + const onAdd = useFunction(() => { + map.on('remove', onRemove); + }) + const onRemove = useFunction(() => { + map.off('remove', onRemove); root.unmount(); }) @@ -117,5 +123,5 @@ export function useRoot( ); }, [props.children]) // eslint-disable-line react-hooks/exhaustive-deps - return { onRemove, useThree, r3m }; + return { onAdd, onRemove, useThree, r3m }; } \ No newline at end of file diff --git a/src/core/generic-map.ts b/src/core/generic-map.ts index f24fda6..f2d990d 100644 --- a/src/core/generic-map.ts +++ b/src/core/generic-map.ts @@ -49,6 +49,7 @@ export interface MapInstance { /** Generic interface of Mapbox/Maplibre `MapEventType` */ export type MapEventType = { resize: MapEvent; + remove: MapEvent; }; /** Generic interface of `MapLibreEvent` or `MapBoxEvent` */