Build a Currency Converter in React
Build a Currency Converter in React: Live Rates, Debounced Inputs, and Clean UX
Creating a currency converter app in React is not only a practical project, but it also provides a great opportunity to improve your development skills. Using live exchange rates from an API like CurrencyRest, you can give users the ability to convert currencies in real-time. In this article, we will walk through how to build a currency converter with debounced inputs and a clean user experience.
Why Use CurrencyRest?
CurrencyRest offers real-time and historical currency exchange rates covering over 180 fiat currencies and around 100 cryptocurrencies. By integrating this API, you can:
- Fetch live exchange rates from central banks and exchanges.
- Get reliable data from sources like ECB, Fed, and Binance.
- Access a generous free plan allowing 300 requests per month.
Setting Up Your React App
First, set up your React environment using Create React App:
npx create-react-app currency-converter
cd currency-converter
npm start
Installing Axios
We'll use Axios to handle API requests. Install it using npm:
npm install axios
Building the Converter Component
Creating the main currency converter component involves handling inputs and displaying results. Below is a simple structure for this component:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const CurrencyConverter = () => {
const [fromCurrency, setFromCurrency] = useState('USD');
const [toCurrency, setToCurrency] = useState('EUR');
const [amount, setAmount] = useState(1);
const [exchangeRate, setExchangeRate] = useState(0);
const [result, setResult] = useState(0);
useEffect(() => {
const fetchExchangeRate = async () => {
try {
const response = await axios.get(`https://api.currencyrest.com/api/v1/convert?from=${fromCurrency}&to=${toCurrency}&amount=${amount}`);
setExchangeRate(response.data.result);
setResult(exchangeRate * amount);
} catch (error) {
console.error('Error fetching exchange rate', error);
}
};
fetchExchangeRate();
}, [fromCurrency, toCurrency, amount]);
return (
<div>
<h1>Currency Converter</h1>
<input type="number" value={amount} onChange={(e) => setAmount(e.target.value)} />
<select onChange={(e) => setFromCurrency(e.target.value)}>
<option value="USD">USD</option>
<option value="EUR">EUR</option>
<option value="XOF">XOF</option>
{/* Add other currencies */}
</select>
<span>to</span>
<select onChange={(e) => setToCurrency(e.target.value)}>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
<option value="XOF">XOF</option>
{/* Add other currencies */}
</select>
<h2>Converted Amount: {result}</h2>
</div>
);
};
export default CurrencyConverter;
Debouncing User Input
To enhance user experience, implement debouncing on the input fields to reduce the number of API calls. You can use a custom useDebounce hook for this purpose. Here's an example:
import { useState, useEffect } from 'react';
const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
};
Now, you can replace the calls to change amount, fromCurrency, and toCurrency with their debounced versions in your main component.
Conclusion
In this tutorial, you learned how to build a simple yet effective currency converter application in React. With the integration of the CurrencyRest API, you can provide accurate, real-time exchange rates to your users.
Don't forget to sign up for CurrencyRest to access 300 requests for free each month and start building your own projects with real-world data!
CurrencyRest
Author