[React] console.log가 두 번 실행되는 이유

Jane·2023년 5월 2일
0

Error Log

목록 보기
1/6
post-thumbnail

Hook 함수를 연습하면서 console.log를 사용할 일이 잦았는데
분명 한 번씩만 넣은 것이 확실함에도
console.log가 두 번씩 실행된다는 사실을 발견했다.

단순히 텍스트만 console 창에 두 번 뜨는 것은 그렇다고 쳐도

  const [count, setCount] = useState(1);
  const renderCount = useRef(1);
  
  useEffect(() => {
    renderCount.current += 1;
    console.log("renderCnt: ", renderCount.current);
  });

이 경우 ref가 처음부터 두 번씩 더해져 3으로 시작하는 것을 보고
함수 자체의 문제인가..? 라는 생각이 들어 공식 문서를 찾아보았다.

링크텍스트

Strict Mode always calls your rendering function twice, so you can see the mistake right away (“Create Story” appears twice). This lets you notice such mistakes early in the process.

console.log()가 두 번 실행되는 것은
Hook 함수의 문제가 아니라 index.js 파일에서 을 감싸고 있는 <React.StrictMode>의 특성이었던 것이다.

모든 경우에 두 번씩 실행되는 것은 아니고,

To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) twice in development. This includes:

  • Your component function body (only top-level logic, so this doesn’t include code inside event handlers)
  • Functions that you pass to useState, set functions, useMemo, or useReducer
  • Some class component methods like constructor, render, shouldComponentUpdate (see the whole list)

아래의 경우에 해당할 때만 두 번씩 실행된다고 하는데
내가 사용한 것이 useState와 set functions에 해당해서 두 번씩 console이 찍힌 것으로 보인다.

개발 도중 발생하는 문제를 더욱 쉽게 발생할 수 있도록 개발자 환경에서만 실행되는 기능이고,
불편하다면 <React.StrictMode> 태그를 삭제하고 사용하면 된다고 한다.

profile
An investment in knowledge pays the best interest🙃

0개의 댓글