const commentPasswordForm = useRef(null);
const handleClickOutside = useCallback((e) => {
if (!commentPasswordForm.current.contains(e.target)) {
commentPasswordForm.current.style.display = 'none';
}
}, []);
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
}, []);
여기서 useEffect는 최초 렌더링때에만 실행 되지만 mousedown 이벤트는 클릭할 때마다 발생한다. 이벤트는 컴포넌트를 빠져나가도 등록되어있으므로 계속 실행된다 따라서 unmount될 때 제거해줘야한다.