Simplifying Currency Conversion in React with Custom Hooks

Simplifying Currency Conversion in React with Custom Hooks

Introduction:

In the vast landscape of web development, creating a currency converter is a common and practical project. As we embark on building our own currency converter in React, we'll explore the power of custom hooks to encapsulate the logic, making our project modular and easy to understand. Join me as we simplify the complexities of currency conversion in simple words.

Setting the Stage: Imagine you're building a React application, and one of its features is a currency converter. Users should be able to input an amount in one currency and get the equivalent amount in another currency. To achieve this, we'll use a custom hook named useCurrencyConverter.

Step 1: Defining the Project Structure

Let's start by organizing our project. Create a new React app or use an existing one. Then, inside your src folder, create a new file called useCurrencyConverter.js to house our custom hook.

Step 2: Creating the useCurrencyConverter Hook

Open useCurrencyConverter.js and begin defining your custom hook. This hook will handle the logic for fetching exchange rates and performing currency conversions.

// useCurrencyConverter.js
import { useState, useEffect } from 'react';

const useCurrencyConverter = () => {
  const [exchangeRates, setExchangeRates] = useState({});
  const [amount, setAmount] = useState(1);
  const [fromCurrency, setFromCurrency] = useState('USD');
  const [toCurrency, setToCurrency] = useState('EUR');
  const [convertedAmount, setConvertedAmount] = useState(null);

  useEffect(() => {
    // Fetch exchange rates from an API (e.g., fixer.io)
    const fetchExchangeRates = async () => {
      try {
        const response = await fetch(
          `https://api.exchangerate-api.com/v4/latest/${fromCurrency}`
        );
        const data = await response.json();
        setExchangeRates(data.rates);
      } catch (error) {
        console.error('Error fetching exchange rates:', error);
      }
    };

    fetchExchangeRates();
  }, [fromCurrency]);

  useEffect(() => {
    // Perform currency conversion when 'amount' or 'toCurrency' changes
    if (exchangeRates[toCurrency] !== undefined) {
      const converted = amount * exchangeRates[toCurrency];
      setConvertedAmount(converted);
    }
  }, [amount, toCurrency, exchangeRates]);

  return {
    amount,
    setAmount,
    fromCurrency,
    setFromCurrency,
    toCurrency,
    setToCurrency,
    convertedAmount,
  };
};

export default useCurrencyConverter;

Step 3: Using the Custom Hook in Components

Now, let's use our custom hook in a React component. Create a new component file, such as CurrencyConverter.js.

// CurrencyConverter.js
import React from 'react';
import useCurrencyConverter from './useCurrencyConverter';

const CurrencyConverter = () => {
  const {
    amount,
    setAmount,
    fromCurrency,
    setFromCurrency,
    toCurrency,
    setToCurrency,
    convertedAmount,
  } = useCurrencyConverter();

  return (
    <div>
      <h2>Currency Converter</h2>
      <label>
        Amount:
        <input
          type="number"
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
        />
      </label>
      <br />
      <label>
        From Currency:
        <input
          type="text"
          value={fromCurrency}
          onChange={(e) => setFromCurrency(e.target.value)}
        />
      </label>
      <br />
      <label>
        To Currency:
        <input
          type="text"
          value={toCurrency}
          onChange={(e) => setToCurrency(e.target.value)}
        />
      </label>
      <br />
      <p>Converted Amount: {convertedAmount}</p>
    </div>
  );
};

export default CurrencyConverter;

Conclusion:

By encapsulating the currency conversion logic into a custom hook, we've simplified the code and made it reusable. The useCurrencyConverter hook takes care of fetching exchange rates and performing the conversion, while our component focuses on rendering and user interaction.

With this approach, you can easily integrate currency conversion functionality into other parts of your application or create additional converters with minimal effort. Custom hooks in React empower developers to build modular, maintainable, and scalable applications, even when dealing with complex tasks like currency conversion.

Happy coding!