📚강의록📚/스파르타)React
React숙련주차06(React Hooks - useContext(Context API)💫)
과부하가즈아
2023. 6. 30. 00:24
useContext
많은 props로 prop drilling이 너무 깊어지면 유지 보수 및 오류 파악이 힘들어 진다. 그래서 prop drilling이 되는 것 대신에 context API를 사용하게 되는데, useContext hook을 통해 쉽게 전역 데이터를 관리할 수 있게 된다.
💫context API 필수 개념
createContext : context 객체를 생성
Consumer : context 변화 감지
Provider : context 전달(to 하위 컴포넌트)
prop drilling
// App.js
import React from 'react'
import GrandFather from './components/GrandFather'
function App() {
return <GrandFather />
}
export default App
▼
// GrandFather.jsx
import React from 'react'
import Father from './Father';
// GrandFather -> Child 어떤 정보를 알려줘서 Child가 그 내용을 출력
function GrandFather() {
const houseName = '스파르타'
const pocketMoney = 10000;
return <Father houseName={houseName} pocketMoney={pocketMoney} />
}
export default GrandFather
▼
// Father.jsx
import React from 'react'
import Child from './Child'
function Father({houseName, pocketMoney}) {
return (
<Child houseName={houseName} pocketMoney={pocketMoney}/>
)
}
export default Father
▼
// Child.jsx
import React from 'react'
const style = {
color: "red",
fontWeight: "900",
};
function Child({houseName, pocketMoney}) {
return (
<div>
나는 이 집안의 막내에요.<br />
할아버지가 우리 집 이름은 <span style={style} >{houseName}</span>라고 하셨어요. <br />
게다가 용돈도 <span style={style}>{pocketMoney}</span>원만큼이나 주셨답니다.
</div>
)
}
export default Child
context API_useContext
💫context API 필수 개념다시 확
createContext : context 객체를 생성
Consumer : context 변화 감지
Provider : context 전달(to 하위 컴포넌트)
// FamilyContext.jsx
import { createContext } from "react";
export const FamilyContext = createContext(null)
▼
// App.js
import React from 'react'
import GrandFather from './components/GrandFather'
function App() {
return <GrandFather />
}
export default App
▼
// GrnadFather.jsx
import React from 'react'
import Father from './Father';
import { FamilyContext } from "../context/FamilyContext";
// GrandFather -> Child 어떤 정보를 알려줘서 Child가 그 내용을 출력
function GrandFather() {
const houseName = '스파르타'
const pocketMoney = 10000;
// Father컴포넌트로 해당 데이터를 전달할 것
// vlaue안에는 객체로 들어감 (key-vlaue같으면 생략가능)
return (
<FamilyContext.Provider value={{ houseName:houseName, pocketMoney }}>
<Father />
</FamilyContext.Provider>
);
}
export default GrandFather
▼
import React from 'react'
import Child from './Child'
function Father() {
return (
<Child />
)
}
export default Father
▼
// Child.jsx
import React, { useContext } from 'react'
import { FamilyContext } from "../context/FamilyContext";
const style = {
color: "red",
fontWeight: "900",
};
function Child() {
// FamilyContext에서 받아와야하는데
const data = useContext(FamilyContext);
return (
<div>
나는 이 집안의 막내에요.<br />
할아버지가 우리 집 이름은 <span style={style} >{data.houseName}</span>라고 하셨어요. <br />
게다가 용돈도 <span style={style}>{data.pocketMoney}</span>원만큼이나 주셨답니다.
</div>
)
}
export default Child;