반복되는 API 호출은 커스텀 훅으로

Changmok LEE·2025년 10월 4일

반복되는 API 호출은 커스텀 훅으로.

매번 api 호출을 반복하다 보면 같은 로직에 변수 이름만 다른 경우가 허다하다. 이를 효율적으로 관리하고자 한다면?

그럴때는 커스텀 훅을 통해 공콩화 작업을 해주자

import { useEffect, useState } from 'react';
import apiClient from '../../api/apiClient';

const useFetch = <T>(url: string, options: any = {}) => {
  const [data, setData] = useState<T | null>(null);
  const optionsString = JSON.stringify(options);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await apiClient<T>(url, options);
        setData(response.data);
      } catch (error) {
        // TODO: 에러 핸들링 로직 추가
        console.error('Error fetching data:', error);
      }
    };
    fetchData();
  }, [url, optionsString]);
  return { data };
};

export default useFetch;
profile
이창목

0개의 댓글