react-mapbox-gl
react-mapbox-gl copied to clipboard
onClick does not see state hooks changes
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.
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>
}
I couldn't figure this out and it was making me pull my hair out. your workaround is great for now, thank you!
Thank you it helped my problem.
@josdejong Thank you!