Originally published on clintech.me
If you've integrated Google Maps into a React app and seen
Autocomplete randomly stop working, Directions silently fail,
or the API throw google is not defined on second render —
you've hit the duplicate loading bug.
Here's exactly what caused it in my case and how I fixed it.
The setup that broke things
While building delivery address flows at
POLOM — a production e-commerce platform —
I integrated Google Places Autocomplete across 20+ screens.
I had the Maps JavaScript API loading in two places:
- A
provider.tsxfor global script loading across the app - A
useLoadGoogleMapshook inside a shared component
This caused race conditions. The Autocomplete and Directions
APIs were initialising before the script fully resolved in some
renders, silently failing in others. The failure wasn't
consistent, which made it harder to catch.
The fix
Step 1 — Remove the global load
Delete the script tag or next/script call in provider.tsx.
There should be exactly one place the Maps API loads.
Step 2 — Centralise in a hook
Move all loading logic into a single useLoadGoogleMaps hook
using dynamic loading. If you're on Next.js, next/script
with strategy="afterInteractive" inside the hook is the
right approach.
Step 3 — Guard before initialising
if (!window.google?.maps) return;
Check that the API is fully available before attempting to
attach Autocomplete or Directions. Don't assume the script
load event means every namespace is ready.
Step 4 — Scope your ref correctly
Bind the autocomplete instance to inputRef.current explicitly.
If the component remounts, re-initialise the binding — don't
assume the previous instance is still attached.
The result
One load, one source of truth, no race conditions. Autocomplete
and Directions worked consistently across all 20+ screens
without reinitialising on every render.
Security — the step most developers skip
Restrict your API key at the Google Cloud Console level:
-
HTTP referrers: whitelist your domain only
(e.g.
https://yourapp.com/*) - API restrictions: enable only the services you actually use — Maps JavaScript API, Places, Directions. Nothing else.
An unrestricted Maps key on a public frontend will get scraped
and abused. It happens faster than you'd expect.
I'm a frontend engineer open to remote EU roles —
connect on LinkedIn
if this was useful.
Top comments (0)