react-mapbox-gl icon indicating copy to clipboard operation
react-mapbox-gl copied to clipboard

onClick does not see state hooks changes

Open josdejong opened this issue 3 years ago • 4 comments

The issue of https://github.com/alex3165/react-mapbox-gl/issues/748 is popping up again in v5.0.0 and newer (v5.1.1). It was fixed in v4.8.6.

In short: when using React hooks, the onClick listener is bound once at initialization it seems, and is not replaced with newer instances of the onClick handler passed with successive renders.

josdejong avatar May 28 '21 07:05 josdejong

Just for reference, the following workaround works for me:

export default function MyComponent({ ... }: MyComponentProps) {
  function handleClick(map: mapboxgl.Map, event: React.SyntheticEvent) {
    // ...
  }

  const handleClickRef = useRef(handleClick)
  handleClickRef.current = handleClick // update reference with every render

  return <div>
    <Mapbox
      // use the reference (which is never changing, only the .current value changes) 
      onClick={(map, event) => handleClickRef.current(map, event)}
      // ...
    >
  </div>
}  

josdejong avatar May 28 '21 07:05 josdejong

I couldn't figure this out and it was making me pull my hair out. your workaround is great for now, thank you!

danielcolinjames avatar Jul 08 '21 00:07 danielcolinjames

Thank you it helped my problem.

Louisduong05 avatar Sep 09 '21 04:09 Louisduong05

@josdejong Thank you!

erinmeyers88 avatar Sep 28 '23 17:09 erinmeyers88