4

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?

norbitrial
  • 14,716
  • 7
  • 32
  • 59
Michael Lynch
  • 2,682
  • 3
  • 31
  • 59
  • 1
    Does this answer your question? [How to fix missing dependency warning when using useEffect React Hook?](https://stackoverflow.com/questions/55840294/how-to-fix-missing-dependency-warning-when-using-useeffect-react-hook) – MrUpsidown Dec 14 '19 at 18:46
  • Not really. If I add `clearMarkers()` into my `useEffect()` I get a different warning prompting me to add `markers` as a dependency and when I do that, I get the same infinite loop. I'm telling React to run the effect every time the `markers` change, and inside the effect, I change the `markers` by clearing them, so I understand why it's looping infinitely. I just don't know how else to accomplish this. – Michael Lynch Dec 14 '19 at 19:05
  • You should consider to use [`@react-google-maps/api`](https://www.npmjs.com/package/@react-google-maps/api). It has [``](https://react-google-maps-api-docs.netlify.com/#marker) component and you can even create your own markers. Then you can just `setMarkers` to a new array with coords and the magic happens. – Christos Lytras Dec 15 '19 at 22:30

2 Answers2

4

You could consider to store markers via mutable ref object (as described here):

const prevMarkersRef = useRef([]);

to distinguish previous markers. And then clear previous markers once locations prop gets updated:

useEffect(() => {
    //clear prev markers 
    clearMarkers(prevMarkersRef.current); 

    //render markers
    for (let loc of props.locations) {
      const marker = createMarker({ lat: loc.lat, lng: loc.lng }, map);
      prevMarkersRef.current.push(marker);
    }
});

where

function createMarker(position, map) {
    return new window.google.maps.Marker({
      position: position,
      map: map
    });
  }

  function clearMarkers(markers) {
    for (let m of markers) {
      m.setMap(null);
    }
  }

Here is a demo

Vadim Gremyachev
  • 57,952
  • 20
  • 129
  • 193
  • 1
    This worked! The functionality works the same and there is no longer a warning, though it feels a little off. I don't think I would've thought to use `useRef()`. I thought that was only for interacting with DOM elements. – Michael Lynch Dec 20 '19 at 01:12
1

You can try and memoize your clearMarkers function and add it to the dependency array of useEffect using useCallback

As your code reads you are creating a new function on each render so the effect is triggered every time if you add the function to the dependency array

this should work

const cb = useCallback(function clearMarkers() {
    for(let i = 0; i < markers.length; i++) {
      markers[i].setMap(null);
    }
  }, [markers.length]);
useEffect(() => {
    cb();
    if (props.locations.length) {
      const googleMarkers = [];
      for (let i = 0; i < props.locations.length; i++) {
        const marker = `marker #${i}`;
        googleMarkers.push(marker);
      }
      setMarkers(googleMarkers);
    }
  }, [props.locations, cb]);

but you can also just add the clearing loop inside useEffect and add the markers.length to the dependency array

Thomas Mery
  • 120
  • 8
  • I did try using `useCallback()` but kept the dependency as `markers`, which resulted in the same infinite loop. I should probably use `useCallback()` anyway, because as you said, the function is created on each render, but the solution may actually be to use `markers.length` as the dependency instead. I will try that out. Thank you for the suggestion. – Michael Lynch Dec 16 '19 at 17:14
  • have you tried the suggested answer? let me know if this worked for you – Thomas Mery Dec 18 '19 at 19:44
  • No, I still got a warning that `markers` was not a dependency even when I added `markers.length` as a dependency, which resulted in the infinite loop. Thanks again for the suggestion though. The solution seems to be to use a mutable ref instead of state. – Michael Lynch Dec 20 '19 at 01:13