[BFE.dev] useRef

치만·2026년 1월 18일

BFE.dev react

목록 보기
13/28
post-thumbnail

useRef

// This is a React Quiz from BFE.dev 

import * as React from 'react'
import { useRef, useEffect, useState } from 'react'
import { createRoot } from 'react-dom/client'

function App() {
  const ref = useRef(null)
  const [state, setState] = useState(1)

  useEffect(() => {
    setState(2)
  }, [])

  console.log(ref.current?.textContent)

  return <div>
    <div ref={state === 1 ? ref : null}>1</div>
    <div ref={state === 2 ? ref : null}>2</div>
  </div>
}

const root = createRoot(document.getElementById('root'));
root.render(<App/>)

출력 결과

undefined
"1"

풀이 과정

1. 초기 렌더링

  • undefined 출력: console.log(ref.current?.textContent)가 실행되는 이때 ref는 초기 상태이므로 null입니다. 아직 아래에 있는 return <div>...</div>가 실행되어 브라우저에 실제 HTML 태그가 만들어지기 전입니다.

    ?. 옵셔널 체이닝은 왼쪽의 값이 null이나 undefined일 경우, 에러를 내는 대신 즉시 실행을 멈추고 undefined를 반환합니다.

  • DOM 생성 및 Ref 연결: React가 화면에 HTML을 그립니다. state1이므로 첫 번째 <div>ref가 붙습니다.


2. 상태 업데이트 후 재렌더링

  • 1 출력: ref.current 아직 이전 렌더링에서 붙어있던 첫 번째<div>를 가리키고 있습니다.
profile
🌱개발 기록장

0개의 댓글