본문 바로가기
개인공부/React

Rules of Hooks

by BTSBRINGMEHERE 2023. 3. 29.

서사

리팩토링을 진행 하던 중 처음보는 에러가 생겨 멘붕이 나갔지만 진짜 별거 아닌 에러라서 금방 해결했습니다.

본문

const { email, password } = useAppSelector((state) => state.user)
const dispatch = useAppDispatch()

 

해당 에러는 이 코드 부분에서 발생을 했습니다. 전혀 이상없는 코드였지만 저는 훅의 규칙을 지키지 않고 작성했기에 에러가 발생했습니다.

 

Hooks can only be called inside the body of a function component.
There are three common reasons you might be seeing it:
1. You might be breaking the Rules of Hooks.
2. You might have mismatching versions of React and React DOM.
3. You might have more than one copy of React in the same app.
Let’s look at each of these cases.

이런 에러 메세지가 발생했고 간략하게

  1. 훅의 규칙을 지키지 않을 수도 있습니다.
  2. 리액트와 리액트 돔의 버전이 맞지 않을 수도 있습니다.
  3. 동일한 앱에 둘 이상의 리액트 복사본이 있을 수도 있습니다.

이렇습니다.

 

다시 본론으로 넘어가서 위의 코드는 리덕스에서 사용되는 상태 관리를 위해서 불러오는 훅인데 저는 첫번 째 오류인 훅의 규칙을 지키지 않아서 에러가 발생했습니다. 

훅의 규칙을 지킨 코드와 그렇지 않은 코드

// ⭕️ Good
const AuthCreate = () => {

  const { email, password } = useAppSelector((state) => state.user);
  const dispatch = useAppDispatch();
  
  .
  .
  .
  
  return (<></>);
}

// ❌ Bad
const { email, password } = useAppSelector((state) => state.user);
const dispatch = useAppDispatch();

const AuthCreate = () => {

.
.
.

  return(<></>);
}

 

정말 간략하게 함수 컴포넌트안에 훅을 넣어야 했는데 그렇지 않았기 때문에 훅의 규칙을 지키지 않았습니다.

정리

처음 보는 에러도 검색하면 다 나오고 천천히 검사하면 금방 찾을 수 있습니다.
하지만 이런 간단한 프로젝트에서나 금방 찾을 수 있지만 콘솔창에서는 어느 부분이 어느 함수가 에러가 발생한지 보이지 않기 때문에 처음 구현할 때 꼼꼼하게 해야겠다는 생각이 들었습니다.

참조

https://react.dev/warnings/invalid-hook-call-warning

 

Rules of Hooks – React

The library for web and native user interfaces

react.dev

 

'개인공부 > React' 카테고리의 다른 글

react-query + recoil  (1) 2023.05.02
Recoil 사용후기  (1) 2023.04.25
Redux Toolkit ...  (0) 2022.12.22
React-infinite-scroll-hook  (1) 2022.11.18
Styled-components  (0) 2022.10.05