惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Blog — PlanetScale
Blog — PlanetScale
J
Java Code Geeks
N
Netflix TechBlog - Medium
Martin Fowler
Martin Fowler
A
About on SuperTechFans
腾讯CDC
B
Blog RSS Feed
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Microsoft Azure Blog
Microsoft Azure Blog
D
Docker
Y
Y Combinator Blog
Microsoft Security Blog
Microsoft Security Blog
F
Fortinet All Blogs
I
InfoQ
博客园 - 【当耐特】
美团技术团队
GbyAI
GbyAI
量子位
宝玉的分享
宝玉的分享
爱范儿
爱范儿
有赞技术团队
有赞技术团队
博客园 - Franky
L
LangChain Blog
阮一峰的网络日志
阮一峰的网络日志

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Localize Prices in React Using Exchange Rates
ApogeoAPI · 2026-05-05 · via DEV Community

ApogeoAPI

Showing prices in a user's local currency increases trust, reduces bounce rates, and improves conversions — especially for international audiences. Here's how to do it automatically in React.

The Goal

  1. Detect the user's currency from their IP address (no user input needed)
  2. Fetch the live exchange rate for that currency
  3. Format the price according to their locale

Step 1: Detect User Currency from IP

// hooks/useCurrency.ts
import { useEffect, useState } from 'react';
export function useCurrency() {
const [currency, setCurrency] = useState('USD');
useEffect(() => {
fetch('https://api.apogeoapi.com/v1/geolocate/auto', {
headers: { 'X-API-Key': process.env.NEXT_PUBLIC_APOGEO_KEY! },
})
.then(r => r.json())
.then(geo => setCurrency(geo.currency ?? 'USD'))
.catch(() => {}); // Fallback to USD on any error
}, []);
return currency;
}

Enter fullscreen mode Exit fullscreen mode

Step 2: Fetch the Exchange Rate

// hooks/useExchangeRate.ts
import { useEffect, useState } from 'react';
export function useExchangeRate(currency: string) {
const [rate, setRate] = useState(null);
useEffect(() => {
if (currency === 'USD') { setRate(1); return; }
fetch(`https://api.apogeoapi.com/v1/exchange-rates/${currency}`, {
headers: { 'X-API-Key': process.env.NEXT_PUBLIC_APOGEO_KEY! },
})
.then(r => r.json())
.then(data => setRate(data.usdRate))
.catch(() => setRate(null)); // Fallback: show USD
}, [currency]);
return rate;
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Format the Price

function formatPrice(usdAmount: number, currency: string, usdRate: number): string {
const localAmount = usdAmount / usdRate;
return new Intl.NumberFormat(undefined, {
style: 'currency',
currency,
maximumFractionDigits: 2,
}).format(localAmount);
}
// Examples:
// formatPrice(19, 'EUR', 1.082) → '€17.56'
// formatPrice(19, 'ARS', 0.001) → 'ARS 19,000.00'
// formatPrice(19, 'BRL', 0.19)  → 'R$100.00'

Enter fullscreen mode Exit fullscreen mode

Step 4: The LocalizedPrice Component

// components/LocalizedPrice.tsx
'use client';
import { useCurrency } from '@/hooks/useCurrency';
import { useExchangeRate } from '@/hooks/useExchangeRate';
interface Props {
usdAmount: number;
className?: string;
}
export function LocalizedPrice({ usdAmount, className }: Props) {
const currency = useCurrency();
const rate = useExchangeRate(currency);
if (rate === null) {
return ${usdAmount};
}
const localAmount = usdAmount / rate;
const formatted = new Intl.NumberFormat(undefined, {
style: 'currency',
currency,
maximumFractionDigits: 2,
}).format(localAmount);
return {formatted};
}

Enter fullscreen mode Exit fullscreen mode

Edge Cases

  • Stale rates: The API returns stale: true if rates are older than 6 hours. Show a small "approximate" indicator in that case.
  • Unknown currency: Always have a USD fallback — the catch(() => {}) blocks above handle this.
  • Loading state: While fetching, show the USD price — it's better than a blank or flashing layout.
  • Server-side rendering: Detect currency server-side in middleware and pass it as a prop or cookie to avoid a layout shift.

Originally published at https://apogeoapi.com/blog/localize-prices-react. Try ApogeoAPI free at apogeoapi.com.