[BFE.dev] React re-render 5 - context

치만·2026년 1월 14일

BFE.dev react

목록 보기
6/28
post-thumbnail

React re-render 5 - context

// This is a React Quiz from BFE.dev 

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

const MyContext = createContext(0);

function B() {
  const count = useContext(MyContext)
  console.log('B')
  return null
}

const A = memo(() => {
  console.log('A')
  return <B/>
})

function C() {
  console.log('C')
  return null
}
function App() {
  const [state, setState] = useState(0)
  useEffect(() => {
    setState(state => state + 1)
  }, [])
  console.log('App')
  return <MyContext.Provider value={state}>
    <A/>
    <C/>
  </MyContext.Provider>
}

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

출력 결과

"App"
"A"
"B"
"C"
"App"
"B"
"C"

풀이 과정

1. 초기 렌더링

  • App 출력: 컴포넌트 트리 상단을 먼저 읽습니다.

  • A 출력: App의 자식인 A를 호출합니다.

  • B 출력: A가 반환한 B를 호출합니다.

  • C 출력: App의 자식인 C를 호출합니다.

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

  • App 출력: 새로운 state 값으로 렌더링합니다.

  • A 출력 X: Amemo를 통해 props가 변하지 않는다면 재렌더링되지 않습니다.

  • B 출력 : BA 안에 있지만, useContext(MyContext)를 통해 컨텍스트값을 받고 있기 때문에 Providervalue의 변경으로 재렌더됩니다.

  • C 출력: App이 재렌더링되면 자식인 C도 무조건 재실행됩니다.

profile
🌱개발 기록장

0개의 댓글