Originally published on — 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
AutocompleteandDirections
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 ornext/scriptcall inprovider.tsx.
There should be exactly one place the Maps API loads.
Step 2 — Centralise in a hook
Move all loading logic into a singleuseLoadGoogleMapshook
using dynamic loading. If you're on Next.js,next/script
withstrategy="afterInteractive"inside the hook is the
right approach.
Step 3 — Guard before initialising
CODEif (!window.google?.maps) return;
Check that the API is fully available before attempting to
attachAutocompleteorDirections. Don't assume the script
load event means every namespace is ready.
Step 4 — Scope your ref correctly
Bind the autocomplete instance toinputRef.currentexplicitly.
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.↗ Original-Artikel auf dev.to lesenVollständiger Original-BerichtAusführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
Ähnliche Beiträge
Auch interessante Nachrichten Debugging the Google Maps Duplicate Loading Bug in React
Thematisch verwandte Begriffe: Debugging, Google, Maps, Duplicate · 6 Treffer
Debug Log #1: I Fixed the Same Error Twice in One Afternoon, and It Still Wasn't Fixed
How I Turned Self-XSS into Reflected XSS (and Bypassed the WAF)
Catching Cross-Language Copy-Paste Debt with Static Analysis and AI Pair-Programmers
OpenAI Confirms AI Agents Wrote to Multiple Internet Sites in ‘Wiki Incident’
Why Most Multi-Agent Systems Fail Even When Evaluation Passes
Videos werden geladen ...
Beiträge werden geladen ...
Videos werden geladen ...
Beiträge werden geladen ...
Videos werden geladen ...
Beiträge werden geladen ...
Videos werden geladen ...
Beiträge werden geladen ...
Videos werden geladen ...
SOCIAL SHARE CARD GENERATOR