티스토리 뷰

반응형

React.js 에서 비동기 요청 등의 동작 이후 응답/set state 가 되기 전에 해당 컴포넌트가 unmount 되면서 set state 오류가 나는 경우가 있다. 그럴때는 아래와 같이 해주면 된다.

 

const mounted = useRef(false);

useEffect(() => {
	mounted.current = true;
    () => {
    	mounted.current = false;
    }
}, []);

const fetch = async () => {
	const res = await fetch();
    if (!mounted.current) {
    	return;
    }
    
    // now mounted. do something else
};
반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2026/11   »
일 월 화 수 목 금 토
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함