
// 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"
App 출력: root.render(<App/>)에 의해 App 컴포넌트가 호출됩니다.
A 출력: App의 자식인 A를 호출합니다.
B 출력: A의 자식인 B를 호출합니다.
C 출력: B의 자식인 C를 호출합니다.
A 출력: 새로운 state 값으로 렌더링합니다.
B 출력: B는 A 안에 있지만, useContext(MyContext)를 통해 컨텍스트값을 받고 있기 때문에 Provider의 value의 변경으로 재렌더됩니다.
C , D 출력 X: A 스스로가 B를 새로 생성한 것이 아니라 App에서 받아온 것이기 때문에 참조값이 동일함(Object.is)으로 A와 컨텍스트값을 받는 B만 재렌더됩니다.