Skip to content

Conversation

@sarimarton
Copy link

React 18 in strict mode simulates an extra unmount + mount cycle in every component's first mount, which results in the rendering effect to run twice with the same conditions, causing a double call to new LeafletMap() which leads to an exception in the leaflet library. There are multiple possibilities described in the official react communication (reactwg/react-18#18) to prevent it, and I tried tearing down the instance (return () => instance.remove()), but it led to other problems, and the code already contains teardown logic. So I went with a state-ref useRef way, where the ref keeps its value over unmounts (as opposed to useState), also described here: reactwg/react-18#18 (reply in thread), so we can effectively prevent the double instantiation.

We still need the const [map, setMap] = useState... part, in order for the useEffect hook to be able trigger a rerender after all the refs are having a value.

React 18 in strict mode simulates an extra unmount + mount cycle in every component's first mount, which results in the rendering effect to run twice with the same conditions, causing a double call to `new LeafletMap()` which leads to an exception in the leaflet library. There are multiple possibilities described in the official react communication (reactwg/react-18#18) to prevent it, and I tried tearing down the instance (`return () => instance.remove()`), but it led to other problems, and the code already contains teardown logic. So I went with a state-ref useRef way, where the ref keeps its value over unmounts (as opposed to useState), also described here: reactwg/react-18#18 (reply in thread), so we can effectively prevent the double instantiation.

We still need the `const [map, setMap] = useState...` part, in order for the useEffect hook to be able trigger a rerender after all the refs are having a value.
@PaulLeCam
Copy link
Owner

React v18 is supported by React Leaflet v4, not v3.

@PaulLeCam PaulLeCam closed this Apr 2, 2022
@gocedillo
Copy link

gocedillo commented Nov 20, 2022

Please, you may consider to include a fix for this issue. You have an awesome library and some projects, like mine right now, is using it to serve a map as a module. In case to want to offer support for React v17.x and v18.x our team has to create two different modules. I think should be great to give support for, at least, React 17 which is not quite old yet

@sarimarton
Copy link
Author

We're also stuck with react-leaflet v3 because of some plugins.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants