Map element reference lost on the dom upon dynamic routing or hot refresh

Hello. I am using Next Js and I have noticed that the reference to the div element where the map is to be mounted is lost whenever react does a hot reload or if the map is on a page which I dynamically route to( routing with next/link )
I will get the error message: Cannot read properties of null (reading ‘id’)
The map also does not display in the div.

However, if I manually reload the page with the map. The reference exists and the map displays.
Here’s my code in useEffect.

const initTomTom = async () => {
                try{
                  const tt = await import('@tomtom-international/web-sdk-maps');
                  await import ('@tomtom-international/web-sdk-maps/dist/maps.css');
                      map.current = tt.map({
                        key: process.env.TOMTOM_KEY,
                        container: mapElement.current.id,
                        center: [stockistInfo?.businessCoords?.long,stockistInfo?.businessCoords?.lat],
                        zoom: 15
                    });
                    var marker = new tt.Marker({draggable:true}).setLngLat([stockistInfo?.businessCoords?.long,stockistInfo?.businessCoords?.lat]).addTo(map.current);
                    marker.on("dragend",()=>setCoords(marker.getLngLat()))
                    return () => map.remove();
                }catch(error){
                  console.log(error.message);
                }
              }
            initTomTom();

Currently the only patch I found was to change all Link tags( to anchor tags () to manually route.

I would appreciate if I could find a better solution here. Thanks

Have you tried following this? Adding TomTom Maps to a Modern React App

@maloleps . Yes. I have followed this. The map displays as it should, however I realized that on hot-reload in development, or if the link is dynamic. The ref to the element where the map is to be mounted is somehow lost, hence the map doesn’t display. It will however display whenever I manually refresh.