Back to Documentation
React Integration Guide
Learn how to integrate FXRateSync API with React using modern hooks and best practices.
Custom Hook Example
Create a reusable React hook for currency conversion:
// hooks/useCurrencyConverter.js
import { useState, useCallback } from 'react'
export const useCurrencyConverter = () => {
  const [result, setResult] = useState(null)
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  const convert = useCallback(async (from, to, amount) => {
    setLoading(true)
    setError(null)
    try {
      const response = await fetch(
        `https://api.fxratesync.io/v1/convert?from=${from}&to=${to}&amount=${amount}`,
        {
          headers: {
            'X-API-Key': process.env.REACT_APP_FX_API_KEY
          }
        }
      )
      if (!response.ok) {
        throw new Error('Conversion failed')
      }
      const data = await response.json()
      setResult(data)
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }, [])
  return { result, loading, error, convert }
}Component Usage
// components/CurrencyConverter.jsx
import React, { useState } from 'react'
import { useCurrencyConverter } from '../hooks/useCurrencyConverter'
export const CurrencyConverter = () => {
  const [from, setFrom] = useState('USD')
  const [to, setTo] = useState('EUR')
  const [amount, setAmount] = useState(100)
  
  const { result, loading, error, convert } = useCurrencyConverter()
  const handleSubmit = (e) => {
    e.preventDefault()
    convert(from, to, amount)
  }
  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <input
        type="number"
        value={amount}
        onChange={(e) => setAmount(e.target.value)}
        placeholder="Amount"
        className="w-full p-3 border rounded-lg"
      />
      
      <select 
        value={from} 
        onChange={(e) => setFrom(e.target.value)}
        className="w-full p-3 border rounded-lg"
      >
        <option value="USD">USD</option>
        <option value="EUR">EUR</option>
        <option value="GBP">GBP</option>
      </select>
      
      <button 
        type="submit" 
        disabled={loading}
        className="w-full bg-primary text-background p-3 rounded-lg"
      >
        {loading ? 'Converting...' : 'Convert'}
      </button>
      
      {result && (
        <div className="p-4 bg-success/10 rounded-lg">
          <p>{result.converted_amount.toFixed(2)} {result.to}</p>
        </div>
      )}
      
      {error && (
        <div className="p-4 bg-destructive/10 text-destructive-foreground rounded-lg">
          {error}
        </div>
      )}
    </form>
  )
}Best Practices
- • Use environment variables for API keys
- • Implement proper error handling
- • Add loading states for better UX
- • Consider caching results to reduce API calls