Search code examples
reactjsgoogle-mapsreact-google-maps

react-google-maps doesn't unmount components when under StrictMode


In the attached example codesandbox I have a Map using react-google-maps. When wrapping the map with <React.StrictMode> it will stop unmounting components.

I see the way react-google-maps unmounts components is usually by setting their map to null using: instance.setMap(null). I don't understand why this behavior should break under StrictMode.

Here's the codesandbox that demonstrates the problem: https://codesandbox.io/s/jv61orz64y

Thanks!
Uri


Solution

  • I had the same issue and came across your issue on the repo and therefore this question. I have gone into detail on the issue as a comment on your repo issue, but to summarise for SO:

    • react-google-maps is a little naughty and actually does some rendering-esque work in the constructor of components. In this case, it initialises the google.maps.Marker and calls setMap. That has the effect of putting the marker on the map.
    • it removes the markers from the map in componentWillUnmount
    • a component may be constructed but never ends up being mounted, when this happens, componentWillUnmount is never called, as there's nothing mounted to unmount
    • this means that if the component is constructed but never mounted, and therefore componentWillUnmount is never called, the marker never gets removed from the map
    • in StrictMode, this exact situation appears to happen, see explanation below:

    If you look at my fork of your demo you'll see that in non-strict mode, the Marker proxy (MyMarker) is constructed, mounted, updated, unmounted and then remounted if you load the page zoom in and then zoom out. However, in strict mode two markers get constructed but only one mounted. So what's happening here is not that the marker is never unmounted as you zoom in, but that there are two markers on the map at all times. One that gets "orphaned" on the map by being constructed but never mounted, and the one that is fully under React's control. It truly is being removed and re-added correctly.