Skip to content

Commit

Permalink
Google Maps: Convert state to refs
Browse files Browse the repository at this point in the history
These are more appropriate for refs than state because they  need to persist across renders, but changing them shouldn't trigger a re-render.
  • Loading branch information
iandunn committed Oct 13, 2023
1 parent 4f203a1 commit 2d1fb84
Showing 1 changed file with 16 additions and 18 deletions.
34 changes: 16 additions & 18 deletions mu-plugins/blocks/google-map/src/components/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ import {
*/
export default function Map( { apiKey, markers: rawMarkers, icon } ) {
const [ loaded, setLoaded ] = useState( false );
const [ clusterer, setClusterer ] = useState( null );
const [ googleMap, setGoogleMap ] = useState( null );
const [ googleMapsApi, setGoogleMapsApi ] = useState( null );
const clusterer = useRef( null );
const googleMap = useRef( null );
const googleMapsApi = useRef( null );
const infoWindow = useRef( null );
let combinedMarkers = [];

Expand All @@ -58,8 +58,8 @@ export default function Map( { apiKey, markers: rawMarkers, icon } ) {
throw 'Google Maps API is not loaded.';
}

setGoogleMap( map );
setGoogleMapsApi( maps );
googleMap.current = map;
googleMapsApi.current = maps;

infoWindow.current = new maps.InfoWindow( {
pixelOffset: new maps.Size( -icon.markerIconAnchorXOffset, 0 ),
Expand All @@ -68,13 +68,11 @@ export default function Map( { apiKey, markers: rawMarkers, icon } ) {
combinedMarkers = combineDuplicateLocations( rawMarkers );
combinedMarkers = assignMarkerReferences( map, maps, infoWindow.current, combinedMarkers, icon );

setClusterer(
clusterMarkers(
map,
maps,
combinedMarkers.map( ( marker ) => marker.markerRef ),
icon
)
clusterer.current = clusterMarkers(
map,
maps,
combinedMarkers.map( ( marker ) => marker.markerRef ),
icon
);

setLoaded( true );
Expand All @@ -84,26 +82,26 @@ export default function Map( { apiKey, markers: rawMarkers, icon } ) {
* Update the map whenever the supplied markers change.
*/
useEffect( () => {
if ( ! clusterer ) {
if ( ! clusterer.current ) {
return;
}

infoWindow.current.close();

combinedMarkers = combineDuplicateLocations( rawMarkers );
combinedMarkers = assignMarkerReferences(
googleMap,
googleMapsApi,
googleMap.current,
googleMapsApi.current,
infoWindow.current,
combinedMarkers,
icon
);

const markerObjects = combinedMarkers.map( ( marker ) => marker.markerRef );

updateMapMarkers( clusterer, markerObjects, googleMap );
panToCenter( markerObjects, googleMap, googleMapsApi );
}, [ clusterer, rawMarkers ] );
updateMapMarkers( clusterer.current, markerObjects, googleMap.current );
panToCenter( markerObjects, googleMap.current, googleMapsApi.current );
}, [ rawMarkers ] );

return (
<div className="wporg-google-map__container">
Expand Down

0 comments on commit 2d1fb84

Please sign in to comment.