React Component for Automatic Local Currency Detection and Formatting
Patch: implement useCurrency and useExchangeRate hooks to auto‑detect user currency via Apogeo API and format prices with Intl.NumberFormat.
Patch: add useCurrency and useExchangeRate hooks to your project, set NEXT_PUBLIC_APOGEO_KEY, and replace hard‑coded prices with <LocalizedPrice> component.
Summary
The article introduces a set of React hooks and a component that automatically detect a visitor’s currency from their IP address, fetch the live exchange rate, and format prices according to the user’s locale. The `useCurrency` hook calls the Apogeo API to geolocate the visitor and sets the currency state, defaulting to USD on error. The `useExchangeRate` hook fetches the exchange rate for the detected currency, again defaulting to 1 for USD. The `formatPrice` function converts a USD amount to the local currency using the fetched rate and formats it with `Intl.NumberFormat`. Finally, the `LocalizedPrice` component ties everything together, rendering the formatted price and accepting a `usdAmount` prop. The implementation includes graceful fallbacks and requires the `NEXT_PUBLIC_APOGEO_KEY` environment variable.
This solution eliminates hard‑coded currency strings and improves international user experience with minimal code changes. It also demonstrates how to keep API keys out of the client bundle by proxying the request in production.
The hooks are lightweight, reusable, and can be dropped into any React project that needs dynamic pricing.
Key changes
- useCurrency hook fetches geolocation from Apogeo API and sets currency state
- useExchangeRate hook fetches rate from Apogeo API, defaults to 1 for USD
- formatPrice converts USD to local amount and formats with Intl.NumberFormat
- LocalizedPrice component uses both hooks to display price
- Fallback to USD on any error
- API key stored in NEXT_PUBLIC_APOGEO_KEY
- Hooks are reusable across projects
- No hard‑coded currency strings required