
// 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"
App 출력: 컴포넌트 트리 상단을 먼저 읽습니다.
A 출력: App의 자식인 A를 호출합니다.
B 출력: A가 반환한 B를 호출합니다.
C 출력: App의 자식인 C를 호출합니다.
App 출력: 새로운 state 값으로 렌더링합니다.
A 출력 X: A는 memo를 통해 props가 변하지 않는다면 재렌더링되지 않습니다.
B 출력 : B는 A 안에 있지만, useContext(MyContext)를 통해 컨텍스트값을 받고 있기 때문에 Provider의 value의 변경으로 재렌더됩니다.
C 출력: App이 재렌더링되면 자식인 C도 무조건 재실행됩니다.