TIL.React Hooks_useContext


Contextとは?


コンテキストは、propsをすべてのレベルで手動で渡す必要がなく、コンポーネントツリーを介してデータを転送する方法を提供します.
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