개발자가 스스로 커스텀한 훅을 의미하며 이를 이용해 반복되는 로직을 함수로 뽑아내어 재사용할 수 있다.
여러 url을 fetch할 때, 여러 input에 의한 상태 변경 등 반복되는 로직을 동일한 함수에서 작동하게 하고 싶을 때 커스텀 훅을 주로 사용한다. 이를 이용하면 3가지의 장점이 있다.
useSomething)커스텀 훅을 정의할 때는 useFetch, useInputs과 같이 함수 이름 앞에 use를 붙이는 것이 규칙이며 보통 프로젝트 내의 hooks 디렉토리에 커스텀 훅을 위치시킨다. 커스텀 훅을 작성할 때는 useState와 같은 React 내장 훅을 사용하여 작성할 수 있다. 그리고 보통의 함수와 마찬가지로 사용자가 직접 파라미터와 반환 값을 결정할 수 있다.
useFetch.js
const useFetch = ( initialUrl:string ) => {
const [url, setUrl] = useState(initialUrl);
const [value, setValue] = useState('');
const fetchData = () => axios.get(url).then(({data}) => setValue(data));
useEffect(() => {
fetchData();
},[url]);
return [value];
};
export default useFetch;
useInputs.js
import { useState, useCallback } from 'react';
function useInputs(initialForm) {
const [form, setForm] = useState(initialForm);
// change
const onChange = useCallback(e => {
const { name, value } = e.target;
setForm(form => ({ ...form, [name]: value }));
}, []);
const reset = useCallback(() => setForm(initialForm), [initialForm]);
return [form, onChange, reset];
}
export default useInputs;