[에러] Error : React Hook "useEffect" is called conditionally

Ju Young Jun·2022년 8월 28일
0

개발 중 마주친 에러

React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?

Hook이 조건부로 선언되었기 떄문이라 한다..

useEffect Hook을 작성하다 에러가 났는데 아래 2원칙중 1번째 원칙에 어긋나서 에러가 났었다.

리액트 Hook의 2원칙

1. Hook은 최상위에서만 선언되어야 한다.

리액트는 Hook이 호출되는 순서에 의존하기 떄문에 Hook의 실행순서가 밀리게 되거나 건너뛰면 버그를 야기한다.

만약 조건부로 Hook을 쓰고 싶다면 Hook 내부에 선언해야 한다.

  useEffect(() => {
    // hooks 최상위 선언부
    const getuserprofile = async () => {
      await GroupService.getGroupOwn()
        .then((res) => res.data.response)
        .then((body) => {
          setOwndata([...owndata, ...body]);
          setIsclick(body[0]);
        });
    };
    if (owndata.length === 0) {
      getuserprofile();
    }
  }, []);

2. 오직 React 함수 내에서만 Hook을 호출해야 한다.

훅을 일반적인 자바스크립트 함수에서 호출하면 안된다. 리액트 함수 컴포넌트나 커스텀 훅에서는 호출이 가능하다.

profile
안녕하세요 :)

0개의 댓글