React에서 커스텀 훅(Custom Hook)은 상태 로직을 재사용할 수 있도록 하는 기능이다. 이는 여러 컴포넌트에서 공통적으로 사용되는 상태 로직을 추출하여 하나의 함수로 만들어 사용할 수 있도록 한다.
💡 반복되는 로직을 리액트 내장 훅 들을 사용하여 개발자가 직접 만든 훅이라고 생각하면 된다.
커스텀훅 네이밍을 use... 형태로 작성해야 한다.
// useFetch.ts
import { useState, useEffect } from 'react';
export const useFetch = (baseUrl: string, initType: string) => {
const [data, setData] = useState(null);
const fetchUrl = (type: string) => {
fetch(baseUrl + '/' + type)
.then((res) => res.json())
.then((res) => setData(res));
};
useEffect(() => {
fetchUrl(initType);
}, []);
return {
data,
fetchUrl
};
};
// App.ts
import { useFetch } from './useFetch';
import * as S from './style';
const baseUrl = 'https://velog.io/@jae2636';
const App = () => {
const { data } = useFetch(baseUrl, 'typeValue');
return (
<S.Container>
// ...
</S.Container>
);
};
export default App;