티스토리 뷰
Context API
작은 규모의 프로젝트에서 사용하면 좋은 React Hook
Context 사용 방법
1. Context 만들기
createContext(기본값)
- Provider가 없는 경우 사용할 default 값(initial X)
// LevelContext.js
import { createContext } from 'react';
export const LevelContext = createContext(1);
2. Context 제공하기
만들어놓은 Context.provider로 Context를 전달하고 싶은 자식 요소 감싸기
→ 트리에 동일한 Context가 여럿 있을 때 자식 요소는 UI 트리에서 가장 가까운 Context 값을 사용
import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
<section className="section">
<LevelContext.Provider value={level}>
{children}
</LevelContext.Provider>
</section>
);
}
3. Context 사용하기
useContext(Context이름)
// Heading.js 저장된 context를 사용할 곳
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
export default function Heading({ children }) {
const level = useContext(LevelContext);
// ...
}
> 중첩 예시
더보기
LevelContext의 기본값 1, Section이 중첩될 때마다 +1된 새로운 Context가 만들어짐
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
export default function Section({ children }) {
const level = useContext(LevelContext);
return (
<section className="section">
<LevelContext.Provider value={level + 1}>
{children}
</LevelContext.Provider>
</section>
);
}
import Heading from './Heading.js';
import Section from './Section.js';
export default function Page() {
return (
<Section>
<Heading>Title</Heading>
<Section>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Section>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Section>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
</Section>
</Section>
</Section>
</Section>
);
}
Context를 사용하기 전 확인할 것
1. props로 전달하는 것이 데이터 흐름을 명확하게 알 수 있음
2. props 전달할 때 하위 컴포넌트가 props를 사용하지 않는 시각적 컴포넌트라면
하위 컴포넌트의 children으로 props가 필요한 요소 넣기
<Layout posts={posts} /> // 대신
<Layout><Posts posts={posts} /></Layout>
위 두 접근방식이 적합하지 않은 경우 Context를 고려
Context 사용 사례
- 테마
- 로그인한 계정
- 라우팅
- 상태 관리
* 참고
리액트 공식문서 context
'Javascript' 카테고리의 다른 글
웹소켓(WebSocket) (0) | 2024.06.24 |
---|---|
CRA(create-react-app)로 만든 프로젝트 vite로 빌드하기 (0) | 2023.08.31 |
[React] rc-rate 라이브러리(별점 컴포넌트) (0) | 2023.06.17 |
[React] react-chartjs-2로 만든 Bar chart에 데이터레이블 추가하기(플러그인) (0) | 2023.06.13 |
[React] 상태가 저장되는 위치: 브라우저의 메모리 (0) | 2023.06.11 |
댓글
공지사항