함수 컴포넌트에서 React State와 생명주기 기능 (lifecycle features)를 연동할 수 있게 해주는 함수입니다.
class없이 React를 사용할 수 있도록 해주는 라이브러리입니다.
https://www.npmjs.com/package/eslint-plugin-react-hook
기본적으로 React에서 제공해주는 hooks들은 아래와 같습니다.
이 built-in hook들은 따로 블로깅을 할 예정입니다.
use
가 앞에 붙는 형식으로 작성됩니다. 예를 들어서 useForm
useQuery
이런식입니다.useState useEffect
와 같은 훅들을 이용해서 제작합니다.아래와 같은 axios.get 함수 코드들이 산더미로 쌓여있다.
로직은 다 똑같다. get, then, catch가 모두 똑같이 들어가있고, url, input과 output 타입만다르다.
//api/getInfoList.ts import axios from 'axios'; import {url} from '@env'; export const getInfoList = (idList: number[]) => { return axios .get(`${url}/list`, { params: { id_list: idList, }, }) .then(response => { return response.data; }) .catch(err => { console.error(err); }); };
이걸 Custom Hook으로 가독성도 좋고, 코드양을 획기적으로 줄일 수 있었다.
hooks/useFecth.hook.ts로 이름을 지어주었다.
//hooks/useFecth.hook.ts import axios from 'axios'; import {baseUrl} from '@env'; import {useEffect, useState} from 'react'; const useFetch = <T>(url: string) => { const [response, setResponse] = useState<T[] | null>(); const [isLoading, setIsLoading] = useState<boolean>(false); const [isError, setIsError] = useState<boolean>(false); useEffect(() => { setIsLoading(true); axios .get(`${baseUrl}/${url}`) .then(res => { setIsLoading(true); setIsError(false); setResponse(res.data); }) .catch(err => { console.error(url, err); setIsLoading(false); setIsError(true); setResponse(null); }); }, [url]); return [response, isLoading, isError] as const; }; export default useFetch;
사용할 때는 아래와 같이 loading 처리만 해주면 간단하게 코드가 사용되는 것을 확인할 수 있습니다.
//pages/index.tsx const [response, isError, isLoading] = useFetch( `url`, ); if(isLoading){ return (...로딩중일 때 띄울 것...) } return (...로딩이 끝났을 때 띄울 것...)
로딩 처리가 쉬워졌습니다.
원래 custom hook을 사용하지 않고 data를 get을 해올때는, 로딩 state을 해당 로직이 사용되는 UX에다가 넣어줘야 했었습니다.
만약 한 페이지에 axios.get이 여러개면, 그 개수만큼 state를 만들어 주었어야 했습니다.
그런걸 그냥 hook하나에서 loading값을 불러오면 되는 로직으로 수정되어 코드짜는데 용이해졌습니다.
https://www.bezkoder.com/react-custom-hook-typescript/
https://ko.legacy.reactjs.org/docs/hooks-intro.html