mapbox / mapbox/mapbox-gl-geocoder
Geocoder input reinitializes repeatedly in dev mode (react + useEffect)
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 388
- Forks
- 181
- PR merge metrics
- No merged PRs in 30d
Description
System Info
---
OS macOS 10.13.6 High Sierra
Node version 14.15
Libraries:
- mapbox-gl
- MapboxGeocoder
- create-react-app
- tailwindcss@2
- craco
Symptoms
---
I'm using the geocoder js library in a react application and seeing that the input is rendered each time my development server restarts (create react app fast refresh). I believe the appropriate enhancement is to provide a clean up function to remove the geocoder on component unmount, similar to the `map.remove()` function provided by `mapboxgl.Map()` as per the [react example repo](https://github.com/mapbox/mapbox-react-examples/blob/master/basic/src/Map.js#L8)
Code sample
---
```
import { useEffect } from 'react'
import mapboxgl from 'mapbox-gl'
import MapboxGeocoder from '@mapbox/mapbox-gl-geocoder'
import '@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css'
const geocoder = new MapboxGeocoder({
accessToken: process.env.REACT_APP_MB_TOKEN,
mapboxgl: mapboxgl
})
export default function Autocomplete() {
useEffect(() => {
geocoder.addTo('#location')
geocoder.on('result', function ({ result }) {
console.dir(result)
})
}, [])
return
}
```
Screenshot
---

Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the geocoder.addTo call in the provided React useEffect and compare its lifecycle with the linked React example's map.remove pattern. Inspect the geocoder control's existing cleanup behavior and determine how unmounting should affect the rendered input and registered result handler. Done means development-server refreshes no longer leave duplicate geocoder inputs.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, react
- Domain
- frontend
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100