이 글은 아래의 링크의 글을 해석한 글입니다.

setInterval() 함수는 주기적으로 인자를 실행하는 함수입니다.

clearInterval() 함수 현재 진행되고 있는 함수의 진행을 멈추는 것에 쓰입니다.

 

 

React의 useEffect() 내부에서 clearInterval()을 사용하는 방법과, 중요한 이유

- setInterval을 지우지 않으면 어떻게 될까요?

const Blinker = ({ text }) => {
  const [visible, setVisible] = useState(true);
  useEffect(() => {
    setInterval(() => {
      console.log(`Current blinking text: ${text}`);
      setVisible((visible) => !visible);
    }, 1000);
  }, [text]);
  return visible ? <h1>{text}</h1> : null;
};

처음 렌더링 될때는, useEffect()이 불리므로 Current blinking text가 1초마다 실행 될 것입니다.

Blinkertext prop 변경하면 어떻게 될까요?

1. useEffecttext에 영향을 받으므로, 다시 렌더링되고, 기능을 다시 실행합니다.

2. 이제는 Current blinking text : a 가 1초간격마다 로그에 찍힐 것입니다.

이 시나리오에서 콘솔 로그는 다음과 같습니다.

처음 렌더링 될 때 setIntervaltext가 변한 후의 setInterval이 함께 존재해서 그렇습니다.

이렇게 되는 것은 원하지 않으므로, 새 interval를 만들기 전에 이전 interval을 삭제해야합니다.

 

 

해결책

const Blinker = ({ text }) => {
  const [visible, setVisible] = useState(true);
  useEffect(() => {
    const intervalId = setInterval(() => {
      console.log(`Current blinking text: ${text}`);
      setVisible((visible) => !visible);
    }, 1000);
    // 정리하는 곳
    return () => {
      clearInterval(intervalId);
    };
  }, [text]);
  return visible ? <h1>{text}</h1> : null;
};

이렇게 되면

1. Blinker prop이 변경되었기 때문에 이전과 동일하게 다시 렌더링 됩니다.

2. React의 useEffect의 종속성을 확인하고, 변경되었기 때문에 기능을 다시 실행합니다.

3. 하지만, 이전과 다르게 먼저 반환된 함수를 실행하여, 이전 효과(interval)를 정리합니다.

4. 이를 통해 Current blinking text : a 만 콘솔 로그에 찍힐 것입니다.

React는 효과를 다시 실행하기 전과, 구성 요소를 마운트 해제할 때 이 정리 기능을 실행합니다.

즉, 기본적으로 변경 사항이 반응하기 전에, 더 이상 구성 요소가 필요하지 않을 때 정리합니다.

 

 

 

https://www.codementor.io/@damianpereira/how-to-use-clearinterval-inside-react-s-useeffect-and-why-it-is-important-1si7mztjlk\

 

How to use clearInterval() inside React's useEffect(), and why it is important. | Codementor

Learn how to properly clear your intervals inside useEffect's cleanup function.

www.codementor.io

 

 

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

 

setInterval() - Web APIs | MDN

The setInterval() method, offered on the Window and Worker interfaces, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.

developer.mozilla.org

 

https://developer.mozilla.org/en-US/docs/Web/API/clearInterval

 

clearInterval() - Web APIs | MDN

The global clearInterval() method cancels a timed, repeating action which was previously established by a call to setInterval(). If the parameter provided does not identify a previously established action, this method does nothing.

developer.mozilla.org

 

+ Recent posts