지금시간?❗️📚 에러노트 - Can't perform a React state update on an unmounted component

Steve·2022년 2월 19일
0

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

시간 넣을라다가 위와 같은 에러가 떴다.

비동기적인 행위를 할 때 unmount되고 나서는 state를 변경할 수 없다는 에러다.
useEffect를 이용해서 return으로 해결하고 unmount시켜야한다.
메모리 누수가 될것이다! 라는 뜻

const [ctime, setCtime] = useState(new Date().toLocaleTimeString());

  const UpdateTime = () => {
    setCtime(new Date().toLocaleTimeString());
  };

  useEffect(() => {
    let timer = setInterval(() => UpdateTime(), 1000);

    return () => {
      clearInterval(timer); // 언마운트 된 컴포넌트의 state는 바꿀수없다. useEffect를 사용해서 없애라.
    };
  });
profile
Front-Dev

0개의 댓글