새로고침시 ref참조 값 null이 되는 에러현상

GI JUNG·2023년 11월 25일
0

react-query

목록 보기
1/4
post-thumbnail

The ref value 'targetElement.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'targetElement.current' to a variable inside the effect, and use that variable in the cleanup function
// ! component를 unmount할 때 targetElement가 있다는 보장이 없으므로
// ! react에서는 targetElement의 참조값을 잃어버리기 전에 복사하여
// ! cleanup에서 관찰자 대상을 제거하라는 message가 나온다.
// ! component가 unmount될 때 cleanup function이 실행이 되는데 component가 unmount될 때 ref의 참조값이 바뀔 수 있으므로 이 참조값을 저장하였다가
// ! 올바르게 관찰자 대상을 제거하여 메모리 누수를 방지할 수 있다.
const copyElement = targetElement.current;

return () => {
  copyElement && observer.unobserve(copyElement);
};

// 이는 ref가 DOM Element이기 때문에 어떠한 이유에서 ref가 가리키는 참조값이 바뀔 수 있음을 react가 인지하고 warning하는 것이다.

profile
step by step

0개의 댓글