코드도보통지

3관문. Mount Timing

관문 3 / 7

ref.current가 null인 렌더 타임과 DOM이 연결된 Effect 타임의 차이를 실험으로 확인하라.

📖 이론 비급

Mount Timing: ref는 렌더 중에 null이다

리액트가 컴포넌트를 렌더할 때 ref.current는 아직 null이다. DOM이 실제로 연결되는 시점은 커밋(commit) 단계이며, 그 이후 실행되는 useEffect 안에서만 ref.current가 DOM 노드를 가리킨다.

조건부 렌더링 주의: {show && <div ref={myRef} />}에서 show가 false가 되면 ref.current는 다시 null이 된다.

⚔️ 수련 코드

import { useRef, useEffect, useState } from 'react';

export default function MountTimingDemo() {
  const divRef = useRef(null);
  const [show, setShow] = useState(true);

  // 렌더 중 접근 (항상 null 또는 이전 값)
  console.log('렌더 중 ref:', divRef.current);

  useEffect(() => {
    // TODO: 여기서 divRef.current를 콘솔에 찍어 차이를 확인하라
    console.log('Effect 내 ref:', divRef.current);
  });

  return (
    <div>
      {show && <div ref={divRef} style={{ padding: 16, background: '#eee' }}>DOM 노드</div>}
      <button onClick={() => setShow(s => !s)}>토글</button>
    </div>
  );
}