
useRef를 사용해 DOM에 접근해 사용하려하는 컴포넌트가 있다. 이 컴포넌트가 unmount 될 때 특정 함수를 실행시키고자 useEffect 내부의 cleanup 함수 내부에 current로 접근해 원하는 결과를 얻으려 했지만 다음과 같은 오류를 출력시켰다.
The ref value 'thumbRef.current' will likely have changed by the time this effect cleanup function runs. If this ref points to a node rendered by React, copy 'thumbRef.current' to a variable inside the effect, and use that variable in the cleanup function.
리액트 17버전 로그를 보면 cleanup 함수에 대한 다음과 같은 설명을 찾을 수 있다.
In React 17, the effect cleanup function always runs asynchronously — for example, if the component is unmounting, the cleanup runs after the screen has been updated.
17버전에서는 cleanup 함수가 비동기로 실행되는데 컴포넌트가 unmonunt 될 때 화면에서 사라지고 나서 cleanup 함수가 실행된다는 것이다.
useEffect(() => {
someRef.current.someSetupMethod();
return () => {
someRef.current.someCleanupMethod();
};
});
useRef로 선언한 somRef는 current 속성을 통해 접근해야 하는데 여기서 someRef.current는 가변성이고 cleanup 함수가 실행되는 순간에는 화면이 업데이트 되고 난 뒤기 때문에 someRef.current의 값은 null로 세팅된다.
개발자 도구를 이용해 current 값을 unmount 이전과 이후를 추적해 보아도 값이 바뀌는것을 볼 수 있다.

해결 방법도 문서에 자세하게 나와있다. 에러 코드를 봐도 알 수 있듯이 useEffect 내부에 current 속성을 미리 할당시켜주고 그 값을 cleanup 함수 내에서 사용하는 것이다.
useEffect(() => {
const instance = someRef.current;
instance.someSetupMethod();
return () => {
instance.someCleanupMethod();
};
});
공식 문서까지 찾아가며 에러의 원인과 해결 방법을 찾아내긴 했지만 에러 메세지를 정확히 보지 않고 검색부터 하는 습관은 고치는 것이 좋을것 같다.
ref : https://ko.legacy.reactjs.org/blog/2020/08/10/react-v17-rc.html#effect-cleanup-timing