async React component effects after unmount 에러 핸들링하기

gak·2023년 1월 10일
0

Handling Async function after unmount

리액트 컴포넌트 내부에서 Async 요청을 보낸 뒤에, 응답을 받기 전에 해당 컴포넌트가 unmount 되면, then 내부 코드가 실행이 될때, 애매한 상황이 연출된다. 이미 컴포넌트는 unmount 되었는데, 컴포넌트에 접근해야 한다니...
그럴경우에 위 이미지와 같은 에러가 뜨게된다.

이런 문제를 막기 위해서 사용할 수 있는 몇가지 방법이 있는데 그 중 내가 사용한건 useMountState 훅스를 만드는 것이다.

export function useMountState() {
  const mountRef = useRef(false);
  const isMounted = useCallback(() => mountRef.current, []);
  
  useEffect(() => {
  	mountRef.current = true;
    
    return () => {
      mountRef.current = false;
    }
  , []}
}

이 훅스를 사용하면, 만약 컴포넌트가 unmount 되었을 경우 isMounted() 의 결과는 false 가 나와서, then 다음 코드를 실행할지 말지 결정할 수 있다.

reference

https://www.benmvp.com/blog/handling-async-react-component-effects-after-unmount/

profile
Hello. I'm Front-End Developer Trying to Create Valuable Things.

0개의 댓글