When exactly does React clean up an effect?
useEffect()
는 리턴값으로 clean up 함수를 전달하여 unmount 할 때의 동작을 설정할 수 있다. 그런데, unmount될 때 동작하면 dependency가 바뀔 때 동작하는 것인지, 아예 렌더링되지 않게 되기 전에 동작하는 것인지 궁금하여 정리했던 내용을 공유한다.
When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time. We’ll discuss why this helps avoid bugs and how to opt out of this behavior in case it creates performance issues later below.
공식 문서에 따르면, effect는 한 번만 동작하는 것이 아니라 매 렌더마다 동작하기 때문에 다음 렌더가 일어나기 전에 이전 렌더의 effect를 clean up 한다고 한다. 즉 dependency가 바뀔 때마다 일어난다. 그 이유는
- effect는 dependency와 관련된 동작
⇒ 따라서 dependency 값이 바뀔 때 마다 cleanup도 일어나야 한다!
ex) api subscribe 1번 유저 → 2번 유저
⇒ 1번 유저에 대한 subscription은 취소되어야 함.
⇒ cleanup으로 예방