Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
clean-up 함수를 사용하게 되면 렌더링이 될 때, 이전에 남은 함수가 실행되어 메모리 누수가 일어나는 일을 막을 수 있다.
useEffect를 사용하여 컴포넌트에서 side effect를 수행하는데, 이때 렌더링이 발생시 메모리 누수가 일어날 수 있다.
🍠 데이터 가져오기, 구독 설정, 수동으로 리액트 컴포넌트 DOM을 수정하는 것이 side effects이다.특히 라우터와 useEffect 훅을 함께 사용한다면 이를 고려해야한다.
react18 버전부터는 메모리 누수에 대한 경고가 사라졌다.
🍓 https://github.com/facebook/react/pull/24195
useEffect(() => {
let lock = false;
if(!lock) {
const timer = setTimeout(() => {
// 3초마다 함수 실행
}, 3000);
}
return () => { lock = true }; // clean-up 함수
}, []);
- 렌더링이 다시 일어날 때 useEffect의 return 함수가 실행된다.
- 실행된 함수가 useEffect의 내부 기능의 작동을 막는다.
- setState나 setTimeout, API 요청과 같은 비동기 함수가 작동할 때 조건문을 걸어 unmount 되지 않았을 때만 실행할 수 있도록 한다.
useRef 사용하기
- 메모리 누수를 해결하기 위해서 useRef로 상태를 구독할 수도 있다.
const unmounted = useRef(false);
useEffect(() => {
if(unmounted.current) {
setState("OK");
}
return () => unmounted.current = true;
}, []);
참고 자료 : https://stackoverflow.com/questions/58038008/how-to-stop-memory-leak-in-useeffect-hook-react, https://ko.reactjs.org/docs/hooks-effect.html
Using the Effect Hook – React
A JavaScript library for building user interfaces
ko.reactjs.org
How to stop memory leak in useEffect hook react
I am using Effect hook to fetch the datas from server and these data are passed to the react table there i have used the same api call to load the next set of datas from server. When the applicatio...
stackoverflow.com
'React' 카테고리의 다른 글
ContextAPI 사용하기 (0) | 2022.11.14 |
---|---|
axios의 interceptors 기능 사용하기 (0) | 2022.11.11 |
코드 깔끔하게 작성하기 (리액트, Styled-Components) (0) | 2022.11.10 |
SuperAgent로 API 호출하기 (0) | 2022.11.10 |
React Query를 통한 실시간 서버 통신 (useQuery hook) (0) | 2022.11.08 |