useJsApiLoader hook and LoadScript component.
useJsApiLoader Hook (Recommended)
TheuseJsApiLoader hook is the recommended approach for loading the Google Maps API. It uses the modern @googlemaps/js-api-loader package and provides better control over the loading state.
Basic Usage
Configuration Options
TheuseJsApiLoader hook accepts the following options:
Your Google Maps API key. Get one from the Google Cloud Console.
Array of Google Maps libraries to load. Available libraries include:
places- Places API for search and autocompletegeometry- Geometry library for calculationsdrawing- Drawing toolsvisualization- Data visualization (heatmaps)marker- Advanced marker features
Version of the Google Maps API to load. Can be
'weekly', 'quarterly', or a specific version number.Language for map labels and controls.
Region biasing for geocoding and place searches.
Array of Map IDs for styling with Google Cloud-based maps styling.
Prevents Google Maps from loading Google Fonts (Roboto).
Referrer policy for API requests.
ID for the injected script tag.
Nonce for Content Security Policy.
Return Value
The hook returns an object with:isLoaded(boolean) -truewhen the API is fully loadedloadError(Error | undefined) - Error object if loading failed
Advanced Example
Performance Tip: Keep the
libraries array as a constant outside your component or use a static class property. Creating a new array on every render will trigger performance warnings and unnecessary reloads.LoadScript Component
TheLoadScript component is an alternative approach that wraps your application and loads the API. It provides a component-based API with loading states.
Basic Usage
LoadScript Props
Your Google Maps API key.
Array of libraries to load.
Custom loading component to display while the API loads.
Callback fired when the API is loaded.
Callback fired if loading fails.
Callback fired when the component unmounts.
Prevents loading of Google Fonts.
ID for the script tag.
API version to load.
Language code.
Region code.
Complete Example
Comparison: useJsApiLoader vs LoadScript
- useJsApiLoader
- LoadScript
Advantages:
- Modern hook-based API
- Better for functional components
- More explicit control flow
- Uses official
@googlemaps/js-api-loader - Lighter weight
- New projects
- Functional components
- Next.js and modern React frameworks
Performance Best Practices
The library will warn you in the console if it detects the
libraries prop changing:
Performance warning! LoadScript has been reloaded unintentionally! You should not pass libraries prop as new array.
Error Handling
Always handle loading errors gracefully:Next Steps
GoogleMap Component
Learn how to use the GoogleMap component
TypeScript Support
Explore TypeScript types and interfaces