I have a React app that displays a map with some markers on it. The map markers are refreshed by clicking a button that fetches new locations from the Google Maps API. I want to remove the previous location markers from the map on each refresh.
import React, { useEffect, useState } from 'react';
function Map(props) {
const [markers, setMarkers] = useState();
function clearMarkers() {
for(let i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
}
useEffect(() => {
clearMarkers();
if(props.locations.length) {
const googleMarkers = [];
for(let i = 0; i < props.locations.length; i++) {
const marker = new window.google.maps.Marker({...});
googleMarkers.push(marker);
}
setMarkers(googleMarkers);
}
}, [props.locations, props.map]);
}
I have it working, but I am getting a warning from React.
React Hook useEffect has a missing dependency: 'clearMarkers'. Either include it or remove the dependency array
I need the dependency array, so the markers only refresh when there are new props.locations
, but when I include it in the dependency array, I get an infinite loop.
How can I clear the markers off the map before adding new ones without React throwing a warning? Or should I not be concerned with the warning?