프로젝트를 개발하던 중 위와 같은 에러를 만났다. 무슨 에러지? 예상보다 적은 훅이 렌더됐다고?
위 에러는 훅 사용보다 앞서서 return 문이 작성됐을 경우에 생기는 에러다. 아주 기본적인 실수를 해서 너무 민망하지만 그래도 다른 분들이 나와 같은 실수를 했을 때 빠르게 해결하시기 위해 공유해본다!
코드를 고치기 전 코드와 코친 후 코드를 작성해 둘테니 참고 바랍니다~!
Before
const EnrollModal = ({ title, enrollModal, toggleEnrollModal }) => {
const [contents, setContents] = useState({ title: '', content: '' });
const titleInput = useRef(null);
const handleFormChange = (e) => {
const changedValue = e.target.name;
const newContents = {
...contents,
};
newContents[changedValue] = e.target.value;
console.log(newContents);
setContents(newContents);
};
const { mutate, data, isLoading, error } = useCreateNotification(contents);
const handleSubmit = () => {
mutate(contents);
};
if (isLoading) return <span>로딩중...</span>;
if (error) return <span>An error has occurred: {error.message}</span>;
// 얘가 문제!
useEffect(() => {
titleInput.current.focus();
}, [enrollModal]);
return ();
}
After
const EnrollModal = ({ title, enrollModal, toggleEnrollModal }) => {
const [contents, setContents] = useState({ title: '', content: '' });
const titleInput = useRef(null);
// return문 전 여기로 이동!
useEffect(() => {
titleInput.current.focus();
}, [enrollModal]);
const handleFormChange = (e) => {
const changedValue = e.target.name;
const newContents = {
...contents,
};
newContents[changedValue] = e.target.value;
console.log(newContents);
setContents(newContents);
};
const { mutate, data, isLoading, error } = useCreateNotification(contents);
const handleSubmit = () => {
mutate(contents);
};
if (isLoading) return <span>로딩중...</span>;
if (error) return <span>An error has occurred: {error.message}</span>;
return ();
}