JustFly1984 / react-google-maps-api

React Google Maps API
MIT License
1.75k stars 426 forks source link

Using useLoadScript across multiple components leads to errors #3277

Closed mschipperheyn closed 11 months ago

mschipperheyn commented 11 months ago

Please provide an explanation of the issue

When you have multiple components on the same page. Or even a sequence of components being loaded as you navigate that may use useLoadScript, the following error occurs that may lead to map rendering errors:

You have included the Google Maps JavaScript API multiple times on this page. This may cause unexpected errors.

Even if you use a single unique map-id to try to guarantee "uniqueness", this will happen.

But, even if the unique map-id would be used as a way to prevent duplicate loading of the api, you could still have the issue that the libraries you may need could vary across different components. Some may need geocoding, some may not.

Your Environment

os: mac

node --version 16

react version: 18

webpack version

@babel version

@react-google-maps/api version 2.19.2

How does it behave?

see above

How should it behave correctly?

I would suggest that the unique map-id should be used as a way to identify a set of libraries to be loaded. If you need to load more libraries, say, one component needs geocoding on top of places, it should use a different map id. The library should figure out which files to load and avoid duplicate loading errors.

Basic implementation of incorrect behavior in codesandbox.com

JustFly1984 commented 11 months ago

As warning states, you can use only one useLoadScript per page.

JustFly1984 commented 11 months ago

PS: use useLoadScript hook higher in the component tree, and pass isLoaded as prop or through the context api, to prevent render those google components until window.google is loaded. PS 2: there could be only one window.google per browser tab. PS 3: you can't render those components on server or in unit testing environment anyway.