Introduction
When I was building a map app using React and Google Maps, I encountered an issue where the pins on the map wouldn’t update when retrieving data from superbase.
The cause of this issue was that “React re-rendering” and “Google Maps re-rendering” operate using completely different mechanisms.
Why Google Maps doesn’t change even when React re-renders
React uses a “virtual DOM” to manage the UI.
In other words, React can only update elements it creates.
On the other hand, Google Maps
internal calls new google.maps.Map() ,
and directly renders the browser DOM.
Since this map runs outside of React,
it doesn’t automatically update even when the React state changes.
This is also explained in the official documentation.
What happens if you change the key?
React has a rule that if the key changes, it is considered a different component.
In other words, if you write something like <Map key={JSON.stringify(filters)} />
,
the key will change every time the filters change. As a result,
<Map>
will be remounted (i.e., regenerated),
and Google Maps will be redrawn with the latest state.
In a nutshell
Since Google Maps runs outside of React, it is not automatically updated when state changes.
Therefore, you can force a redraw by changing the key and remounting it.
Reference Links
-
React Official: Reconciliation (Diffing Algorithm)
https://legacy.reactjs.org/docs/reconciliation.html -
@vis.gl/react-google-maps Official: Map Component Docs
https://visgl.github.io/react-google-maps/docs/api-reference/components/map -
Google Maps API: Overview
https://developers.google.com/maps/documentation/javascript/overview