npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

google-places-autocomplete-hook

v0.1.8

Published

React hook for Google Places Autocomplete on the Places API (New), with session tokens handled for you and a drop-in mode for use-places-autocomplete

Readme

google-places-autocomplete-hook

npm ci size license

A small React hook for Google Places Autocomplete on the Places API (New). Try it with your own key.

Google moved the old Places API and AutocompleteService to legacy status on 1 March 2025. Since then the legacy API is hidden from new projects and left out of new API keys, and Google says that since October 2026 it can no longer be enabled for new Google Cloud projects. Popular hooks such as use-places-autocomplete still depend on it. This package uses the new AutocompleteSuggestion API instead. It keeps one session token per search, so typing and the final details request are billed as a session rather than request by request. It also includes a drop-in mode for use-places-autocomplete.

If the browser console shows LegacyApiNotActivatedMapError ("You're calling a legacy API, which is not enabled for your project") or says AutocompleteService is not available to new customers, your code is calling the legacy Places API. This package calls the new one.

  • Headless: bring your own input and list
  • Session tokens handled for you
  • Debounced, ignores out-of-order responses, safe to unmount mid-request
  • TypeScript types without needing @types/google.maps
  • React 16.8 to 19, works with server rendering, no dependencies

On the server, google-maps-fetch is the companion package: a small client for Places, Routes, Geocoding and the other Maps web APIs, with a drop-in replacement for @googlemaps/google-maps-services-js.

Install

npm install google-places-autocomplete-hook

Set up Google Cloud

  1. In a Google Cloud project with billing turned on, enable Maps JavaScript API and Places API (New). You don't need the legacy "Places API".
  2. Create an API key. Under Application restrictions, choose Websites and add your site, plus the address you develop on (for example http://localhost:5173/*). Under API restrictions, allow the same two APIs.

Load the Maps JavaScript API

<script async src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&loading=async"></script>

Any loader that defines google.maps.importLibrary works too, such as @googlemaps/js-api-loader or the APIProvider from @vis.gl/react-google-maps:

import { APIProvider } from '@vis.gl/react-google-maps'

export const App = () => (
  <APIProvider apiKey={import.meta.env.VITE_GOOGLE_MAPS_KEY}>
    <PlaceSearch />
  </APIProvider>
)

The hook loads the places library itself, and waits for the script if it arrives after your component mounts.

Usage

import { usePlaces } from 'google-places-autocomplete-hook'

export function PlaceSearch() {
  const { ready, value, setValue, suggestions, status, clearSuggestions, getPlace } = usePlaces({
    request: { includedRegionCodes: ['in'] },
  })

  const select = async (suggestion) => {
    setValue(suggestion.text, false)
    clearSuggestions()
    const place = await getPlace(suggestion, ['formattedAddress', 'location'])
    console.log(place.formattedAddress, place.location.lat(), place.location.lng())
  }

  return (
    <div>
      <input value={value} onChange={(e) => setValue(e.target.value)} disabled={!ready} placeholder="Search a place" />
      {status === 'ok' && (
        <ul>
          {suggestions.map((s) => (
            <li key={s.placeId} onClick={() => select(s)}>
              <strong>{s.mainText}</strong> <small>{s.secondaryText}</small>
            </li>
          ))}
        </ul>
      )}
    </div>
  )
}

Options

| Option | Default | | | :------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | request | | Sent with every request: includedRegionCodes, includedPrimaryTypes, language, region, locationBias, locationRestriction, origin, ... (reference) | | debounce | 200 | Milliseconds to wait after typing | | minLength | 1 | Shortest input that fetches suggestions | | defaultValue | '' | | | initOnMount | true | Load the places library on mount |

Returns

| | | | :--------------------------------------------- | :--------------------------------------------------------------------------------------------------------------------------- | | ready | The places library has loaded | | value, setValue(value, shouldFetch = true) | The input value. Pass false to set it without fetching, for example after a selection; that also ends the search's session | | suggestions | { placeId, text, mainText, secondaryText, matches, mainTextMatches, types, distanceMeters, prediction }[] | | status | 'idle', 'ok', 'zero-results' or 'error' | | loading, error | | | clearSuggestions() | Empty the list and ignore any request in flight | | getPlace(suggestion, fields?) | Fetch place details, ending the session the suggestion came from. Default fields: id, formattedAddress, location | | init() | Load the library, if the Maps script loads after the component mounts |

Sessions and billing

Every request while the user types shares one session token. A suggestion remembers the session it came from, so getPlace ends that session whenever you call it, and setValue(text, false) (a selection or a reset) closes the current search so the next keystroke starts a new one. You never handle tokens yourself.

What Google charges for a session depends on how it ends (session pricing):

  • getPlace with Essentials fields only (the default: id, formattedAddress, location; also viewport, addressComponents, types): the first 12 autocomplete requests in the session are billed per request, any beyond that are free, and the details request is billed at Essentials.
  • getPlace with any Pro or Enterprise field (displayName, rating, phone numbers, website, ...): every autocomplete request is free, and the details request is billed at Enterprise + Atmosphere, whatever else you asked for.
  • No getPlace, for example when you only need the suggestion's text or you geocode the address instead: every autocomplete request is billed per request.

So for a box that only needs an address and coordinates, the defaults are the cheapest option. If you need a display name or more, one details request at the top tier buys free autocomplete (field tiers).

Troubleshooting

| What you see | What to check | | :-------------------------------------------- | :----------------------------------------------------------------------------------------------------------------- | | ApiNotActivatedMapError in the console | Maps JavaScript API isn't enabled in the key's project | | RefererNotAllowedMapError | The page's address isn't in the key's list of websites | | ApiTargetBlockedMapError | The key's API restrictions leave out Maps JavaScript API | | status is 'error' with a permission error | Places API (New) isn't enabled, or the key's API restrictions leave it out | | LegacyApiNotActivatedMapError | Something on the page still calls the legacy API (AutocompleteService); this hook doesn't | | ready stays false | The Maps script hasn't loaded: check the script tag or loader, and look in the console for one of the errors above |

Migrating from use-places-autocomplete

Change the import:

- import usePlacesAutocomplete, { getDetails, getGeocode, getLatLng, getZipCode } from 'use-places-autocomplete'
+ import usePlacesAutocomplete, { getDetails, getGeocode, getLatLng, getZipCode } from 'google-places-autocomplete-hook/compat'

The hook returns the same { ready, value, suggestions: { loading, status, data }, setValue, clearSuggestions, clearCache, init }. Each item in data has the legacy prediction shape: description, place_id, structured_formatting, matched_substrings, terms and types.

Differences:

  • requestOptions is converted: componentRestrictions.country becomes includedRegionCodes, types becomes includedPrimaryTypes, and location with radius or bounds becomes locationBias. Google's new API accepts a different list of types, so check yours (supported types).
  • getDetails asks for place_id, formatted_address, geometry and address_components unless you pass fields, all in Google's cheapest tier. The old version asked for every field and was billed for all of them. Adding name or any other Pro or Enterprise field bills the details request at Enterprise + Atmosphere, which in return makes the session's autocomplete requests free (see Sessions and billing). For a place the hook suggested, the details are fetched through that suggestion, which ends its session; the language option then has no effect, since the suggestion already has the hook's language.
  • getGeocode still works, but it doesn't end the autocomplete session, so those requests are billed one by one. Use getDetails with geometry and getLatLng if you only need coordinates.
  • cache, cacheKey and googleMaps are accepted and ignored.
  • status is one of '', 'OK', 'ZERO_RESULTS' or 'UNKNOWN_ERROR'; the type also allows the other legacy values so existing comparisons compile.
  • Coming from 1.x: getLatLng and getZipCode return plain values, not Promises, so await them or use the result directly; .then() on them throws. getZipCode returns undefined rather than null when there is no postal code. The LatLon type is still exported.
  • types: address becomes the street-level types; geocode and establishment have no equivalent in the new API, so no type filter is applied for them.

Example

The demo page runs the hook and /compat against Google with your own key, which stays in your browser, and shows how the requests group into sessions. example/ has the same searches as a minimal project to run locally; example/README.md has the steps.

Contributing

See CONTRIBUTING.md. Please follow the code of conduct, and report security issues as described in SECURITY.md.

License

MIT © Ninad Sutrave

This is an independent project, not affiliated with or endorsed by Google. Google Maps is a trademark of Google LLC.