[BFE.dev] React re-render 6 - Context

치만·2026년 1월 15일

BFE.dev react

목록 보기
9/28
post-thumbnail

React re-render 6 - Context

// This is a React Quiz from BFE.dev 

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

const MyContext = createContext(0);

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

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

function C() {
  console.log('C')
  return null
}

function D() {
  console.log('D')
  return null
}
function App() {
  console.log('App')
  return <A><B><C/></B><D/></A>
}

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

출력 결과

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

풀이 과정

1. 초기 렌더링

  • App 출력: root.render(<App/>)에 의해 App 컴포넌트가 호출됩니다.

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

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

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


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

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

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

  • C , D 출력 X: A 스스로가 B를 새로 생성한 것이 아니라 App에서 받아온 것이기 때문에 참조값이 동일함(Object.is)으로 A와 컨텍스트값을 받는 B만 재렌더됩니다.

profile
🌱개발 기록장

0개의 댓글