모든 레벨에서 수동적으로 props를 전달하는 거 없이, context는 컴포넌트 트리를 통해 데이터를 전달할 방법을 제공한다.
import React from 'react'
import ComponentC from './components/ComponentC'
export const UserContext =React.createContext()
export const ChannelContext=React.creatContext()
function App(){
return(
<div className="App">
<UserContext.Provider value={'chloe'}>
<ChannelContext.Provider value={'code'}>
<ComponentC/>
</ChannelContext.Provider>
</UserContext.Provider>
</div>
)
}
export default App
import React from 'react'
import {UserContext,ChannelContext} from '../App'
function ComponentF(){
return(
<div>
<UserContext.Consumer>
{
user=>{
return (
<ChannelContext.Consumer>
{
channel=>{
return <div> User context value {user},channel context value {channel}
</div>
)
user에 app component에서 username으로 정한 chloe가 찍힌다!
}}
</ChannelContext.Consumer>
)
}}
</UserContext.Consumer>
</div>
)
}
export default ComponentF
import React, {useContext} from 'react'
import ComponentF from './ComponentF'
import {UserContext, ChannelContext} from '../App'
function ComponentE(){
const user =useContext(UserContext)
const channel = useContext(ChannelContext)
return (
<div>
{user} -{channel}
</div>
)
}
export default ComponentE