React hook for fetching WooCommerce allowed countries and country states for address forms
A client-side React hook that fetches the list of allowed countries and, optionally, the states/provinces for a selected country. Used primarily by address forms in checkout and account pages.
Source: hooks/useCountries/useCountries.ts
import { useCountries } from '@/hooks/useCountries'; import { CountriesEnum } from '@/graphql'; function AddressForm() { const [selectedCountry, setSelectedCountry] = useState<CountriesEnum>(); const { countries, states } = useCountries(selectedCountry); return ( <> <select onChange={(e) => setSelectedCountry(e.target.value as CountriesEnum)}> {countries.map((c) => ( <option key={c.code} value={c.code}>{c.name}</option> ))} </select> {states.length > 0 && ( <select> {states.map((s) => ( <option key={s.code} value={s.code}>{s.name}</option> ))} </select> )} </> ); }
| Parameter | Type | Required | Description |
|---|---|---|---|
country | CountriesEnum | No | When provided, fetches the states/provinces for that country |
| Property | Type | Description |
|---|---|---|
countries | Country[] | List of allowed countries with name and code |
states | CountryState[] | States/provinces for the selected country (empty if no country selected) |
The Country type has name: string and code: CountriesEnum.
On mount - Initializes countries with default values derived from the CountriesEnum using Intl.DisplayNames for human-readable country names. Immediately fetches the allowed countries list from /api/countries (revalidates every 24 days).
When country changes - Fetches states from /api/countries/{countryCode} with aggressive caching (revalidates every 365 days). If country is not provided, states remains an empty array.
| Route | Method | Description |
|---|---|---|
/api/countries | GET | Returns the list of WooCommerce allowed countries |
/api/countries/{code} | GET | Returns states/provinces for a specific country |
The generated spec file (useCountries.spec.ts) mocks apiCall and verifies: