11.15 TIL useContext

이정민·2022년 11월 17일
0

useContext :리액트 내부적으로 state를 관리할 수 있게 만드는 장치(prop chain필요 없음)

  1. store 폴더 생성
  2. store폴더 안에 -context.js(케밥케이스)작성
const AuthContext = React.createContext({
isLoggedIn:false
}) //컨텍스크(빈 state의 컴포넌트) 객체를 생성
//컴포넌트가 되거나 , 컴포넌트를 포함하는 객체가 될 것 
//여기서 AuthContext는 컴포넌트가 아닌 컴포넌트를 포함하는 객체 
export default AuthContext 
//이 컨텍스트를 이용하려면 Provide, consume해야함  
  1. app.js에 들어가서 해당되는 범위를 AuthContext.Provider로 묶어준다.
<AuthContext.Provider value={{isLoggedIn: isLoggedIn}}></AuthContext.Provider> 
  1. 이 값에 접근하려면 리스닝을 해야한다. 이때 Context.Consumer(6번) 혹은 리액트 훅(useContext/ 7번 방법 )을 사용한다
  2. 데이터가 필요한 모든 것을 Context.Consumer 로 감싸준다. (Consumer는 함수인 자식을 가져야한다.)
<AuthContext.Consumer>
{(ctx)=>{
return (
<div>
 해당 데이터에 접근할 수 있는 jsx코드 

ctx.isLoggedIn
</div>
)}
</AuthContext.Consumer>
import {useContext} from "react"

const ctx = useContext(AuthContext)

0개의 댓글