
// 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"
undefined 출력: console.log(ref.current?.textContent)가 실행되는 이때 ref는 초기 상태이므로 null입니다. 아직 아래에 있는 return <div>...</div>가 실행되어 브라우저에 실제 HTML 태그가 만들어지기 전입니다.
✨
?.옵셔널 체이닝은 왼쪽의 값이null이나undefined일 경우, 에러를 내는 대신 즉시 실행을 멈추고undefined를 반환합니다.
DOM 생성 및 Ref 연결: React가 화면에 HTML을 그립니다. state가 1이므로 첫 번째 <div>에 ref가 붙습니다.
1 출력: ref.current 아직 이전 렌더링에서 붙어있던 첫 번째<div>를 가리키고 있습니다.