Custom Hook을 이용한 상품 추천 기능 추가하기

상품 추천 기능은 사용자에게 관련 상품을 보여주는 기능으로, 웹 애플리케이션의 사용자 경험을 향상시키는 데 도움이 됩니다. 이 기능을 추가하기 위해 Custom Hook을 활용할 수 있습니다. Custom Hook은 React의 훅 시스템을 이용하여 로직을 재사용하는 방법입니다.

Custom Hook이란?

Custom Hook은 React의 훅 시스템을 이용하여 로직을 캡슐화하고 재사용하는 함수입니다. 이를 통해 컴포넌트 간에 공통된 로직을 추상화할 수 있으며, 코드의 가독성과 유지보수성을 향상시킬 수 있습니다.

상품 추천 기능을 위한 Custom Hook 작성하기

먼저, useProductRecommendation이라는 Custom Hook을 작성해 보겠습니다. 이 Hook은 API로부터 상품 추천 데이터를 가져오고, 해당 데이터를 상품 목록으로 변환하는 역할을 수행합니다.

import { useState, useEffect } from 'react';

const useProductRecommendation = (userId) => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // API로부터 상품 추천 데이터를 가져옵니다.
    fetch(`/api/recommendations?userId=${userId}`)
      .then((response) => response.json())
      .then((data) => {
        // 상품 추천 데이터를 상품 목록으로 변환합니다.
        const productList = data.map((entry) => ({
          id: entry.id,
          name: entry.name,
          price: entry.price,
        }));
        setProducts(productList);
      });
  }, [userId]);

  return products;
};

export default useProductRecommendation;

위 코드에서 useEffect는 컴포넌트가 마운트될 때와 userId가 변경될 때마다 실행됩니다. API로부터 상품 추천 데이터를 가져와 products 상태를 업데이트합니다.

상품 추천 기능 사용하기

위에서 작성한 useProductRecommendation Hook을 사용하여 상품 추천 기능을 구현해 보겠습니다. 예를 들어, ProductRecommendation 컴포넌트에서 해당 Hook을 사용하여 추천 상품을 가져오고 렌더링하는 예제입니다.

import useProductRecommendation from './useProductRecommendation';

const ProductRecommendation = ({ userId }) => {
  const products = useProductRecommendation(userId);

  return (
    <div>
      <h2>추천 상품</h2>
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            <strong>{product.name}</strong> - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default ProductRecommendation;

ProductRecommendation 컴포넌트에서 useProductRecommendation Hook을 사용하여 products 값을 가져오고, 이를 바탕으로 추천 상품 목록을 렌더링합니다.

결론

Custom Hook을 이용하여 상품 추천 기능을 추가하는 방법에 대해 알아보았습니다. Custom Hook은 React에서 로직을 재사용하기 위한 강력한 도구이며, 컴포넌트 간의 공통된 로직을 추상화하여 코드의 가독성과 유지보수성을 향상시킬 수 있습니다.