-
3월 18일 TIL : context API, props전송없이 state를 공유하는 방법Java Script & Type Script/TIL 2023. 3. 18. 21:05728x90
상태관리 라이브러리없이 props전송없이 state공유가 가능한 방법이 있다.
그건 바로 context API
근데 잘 안쓰는 이유는,
1. 성능이슈
2. 컴포넌트 재활용이 어렵다
로 인해 잘 이용은 안함.컴포넌트 바깥에
const Context1= createContext()
이렇게 만들어준다. 그리고
state를 공유할 부분에
<Context1.Provider value={{ shoes }}> <Detail/> </Context1.Provider>
이렇게 감싸주고,
전송할 데이터를 value={{여기안에넣으면된다}}
그리고 Detail 컴포넌트로 임포트를 해주고,import { Context1 } from "./App";
const {shoes}=useContext(Context1);
useContext를 이용해 보관함을 해체한다.
그리고 이제 자유롭게 쓰면되는데,
아까 언급한 것 처럼 state 변경시 쓸데없는 컴포넌트까지 전부 재렌더링이 되고,
useContext() 를 쓰고 있는 컴포넌트는 나중에 다른 파일에서 재사용할 때 Context를 import 하는게 귀찮아질 수 있다.
728x90'Java Script & Type Script > TIL' 카테고리의 다른 글
3월 26일 TIL : ReactQuery 시작하기 (0) 2023.03.26 3월 23일 TIL : TS-Overloading, Polymorphism [타입스크립트야... 내가 명시도안했는데 타입을 유추한거야?] (0) 2023.03.24 3월 21일 TIL : TypeScript-call signature, unknown,void,never (0) 2023.03.23 3월 18일 TIL : TypeScript 시작 (0) 2023.03.21 3월18일 TIL : automatic batch (2) 2023.03.18