Javascript/React

[React/Recoil] ⚓️ useResetRecoilState 사용시, hook 에러

발생오류

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the

문제 : useResetRecoilState를 함수에서 바로 실행시켰더니 "Invalid hook call" 문제 발생

 

원인 : useResetRecoilState는 hook이다. hook은 function component 내부에서만 선언 가능하다. 하지만, clearLogin이라는 함수에서 hook을 실행시켰기에 오류 발생.

 

해결 : function component 내부에서 useResetRecoilState를 실행시키고, 이를 다른 변수에 할당한다. 그리고 해당 변수를 함수로써 실행

 

 

오류 코드

  const clearLogin = () => {
    //auth에서 사용중인 recoil 초기화
    useResetRecoilState(UserAtom);
    useResetRecoilState(LoginTokenAtom);
  };

 

올바른 코드

  const clearUserAtom = useResetRecoilState(UserAtom);
  const clearLoginTokenAtom = useResetRecoilState(LoginTokenAtom);
  const clearLogin = () => {
    //auth에서 사용중인 recoil 초기화
    clearUserAtom();
    clearLoginTokenAtom();
  };

 

 

 

배운 곳

728x90
반응형