title: Clearing map layers with react-leaflet and hooks
body: <p>I'm building a custom plugin for <code>react-leaflet</code> to locate the user using leaflet's <a href="https://leafletjs.com/reference-1.6.0.html#map-locate" rel="nofollow noreferrer">locate</a> method. </p>
  
  <p>It works basically, but with the one problem of the layer not clearing between turning location off and back on again. Each time the locate button is toggled, <code>locate</code> should start fresh. </p>
  
  <p>Here is a <a href="https://codesandbox.io/s/react-leaflet-problem-not-clearing-layers-on-locate-vvyrj" rel="nofollow noreferrer">codesandbox</a> of the problem. As you toggle the button, the circle becomes darker as the layers are stacked on top of each other.</p>
  
  <p>Here is the component:</p>
  
  <pre><code>import React, { useEffect, useState, useRef } from 'react'
  import L from 'leaflet'
  import { useLeaflet } from 'react-leaflet'
  import LocationSearchingIcon from '@material-ui/icons/LocationSearching';
  import MapButton from './MapButton'
  
  function Locate() {
  
    const { map } = useLeaflet();
  
    const [locate, setLocate] = useState(false);
  
    function toggleLocate() {
      setLocate(!locate)
    }
  
    console.log(locate)
  
    const layerRef = useRef(L.layerGroup());
  
    useEffect(() =&gt; {
  
      if (locate) {
        map.removeLayer(layerRef.current)
        map.locate({ setView: false, watch: true, enableHighAccuracy: true }) /* This will return map so you can do chaining */
          .on('locationfound', function (e) {
            L.circleMarker([e.latitude, e.longitude], {
              radius: 10,
              weight: 3,
              color: 'white',
              fillColor: 'blue',
              fillOpacity: 1
            }).addTo(layerRef.current);
            L.circle([e.latitude, e.longitude], e.accuracy / 2, {
              weight: 1,
              color: 'blue',
              fillColor: 'blue',
              fillOpacity: 0.2
            }).addTo(layerRef.current);
            window.localStorage.setItem('accuracy', e.accuracy)
            map.setView([e.latitude, e.longitude], 16)
            layerRef.current.addTo(map)
          })
          .on('locationerror', function (e) {
            alert("Location error or access denied.");
          })
      } if (!locate) {
        map.stopLocate();
        map.removeLayer(layerRef.current);
      }
    }, [locate, map]);
  
    return (
      &lt;MapButton
        title={locate ? 'Click to disable location' : 'Click to locate'}
        onClick={toggleLocate}
        left
        top={102}
      &gt;
        &lt;LocationSearchingIcon fontSize="small" style={{ color: locate ? 'orange' : '' }} /&gt;
      &lt;/MapButton&gt;
    )
  }
  
  export default Locate
  </code></pre>
  
  <p>I would appreciate any solution or tips to stop the layers stacking, and clear properly went the button is toggled. Thanks</p>