[BFE.dev] useRef II

치만·2026년 2월 2일

BFE.dev react

목록 보기
28/28
post-thumbnail

useRef II

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

function App() {
  const ref = useRef()
  
  console.log(!!ref.current)
  useEffect(() => {
    console.log(!!ref.current)
  }, [ref.current]) 

  const [state, setState] = useState(0)
  console.log(1)
  
  useEffect(() => {
    console.log(2)
    setState(state => state + 1)
  }, [])

  return <div ref={ref}/>
}

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

출력 결과

false
1
true
2
true
1
true

풀이 과정

1. 초기 렌더링

  • false 출력: root.render(<App />)가 실행되면서 ref의 초기값은 undefined이므로 false가 출력됩니다.
  • 1 출력: 1이 출력됩니다.

  • true 출력: DOM 엘리먼트를 생성한 뒤 첫 번째 useEffect를 통해 ref.currentdiv를 가리키고 있기 때문에 true가 출력됩니다.

  • 2 출력: 두 번째 useEffect를 통해 2이 출력됩니다.

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

  • true 출력: ref는 아까와 마찬가지로 div를 담고 있기 때문에 true가 출력됩니다.

  • 1 출력: 1이 출력됩니다.

  • true 출력: useEffect를 통해 true가 출력됩니다.

profile
🌱개발 기록장

0개의 댓글