Fix duplicate leaflet instantiation in React 18 strict mode #964
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.