리엑트 class 컴포넌트 내에서 componentWilUnmount의 경우 주로 이벤트 리스너를 지울때 사용한다.
예를들어 setInterval같은 경우, 컴포넌트가 없어졌을 때 계속 실행되고 있으면 안되기 때문에 componentWillUnmount라이프 사이클에 맞춰 clean up 해준다. 그렇다면 훅스에서는 어떻게 이를 처리할까?
useEffect를 사용해서 componentWillUnmount의 효과를 낼 수 있다. 아래 리엑트 공식문서에 나오는 방법을 참고하자.
useEffect내에서 함수를 return하며 그 함수 안에 로직을 작성해주면 된다.
import React, { useState, useEffect } from 'react';
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
'React.JS' 카테고리의 다른 글
Prop `className` did not match (0) | 2022.01.18 |
---|---|
React.js와 Codeigniter 연결하기 (0) | 2021.04.26 |
react직접 만들어 보기(2) _ render 메서드 구현 (0) | 2021.01.02 |
react 직접 만들어 보기(1)_가상돔 만들기 (0) | 2020.11.30 |
redux-thunk 알아보기 (0) | 2019.11.24 |