웹프로그래밍/React
[React.js] unmounted component memory leak
jihun202
2020. 8. 28. 16:58
반응형
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
};
반응형