https://react.dev/learn/passing-data-deeply-with-context
Passing Data Deeply with Context – React
The library for web and native user interfaces
react.dev
위 글을 참고하여 작성하였습니다.
1. The problems with passing props
React 컴포넌트는 props를 통해 부모에서 자식으로 데이터를 넘겨준다.
하지만, 컴포넌트 구조의 깊이가 깊어 데이터를 보여주어야 할 자식 컴포넌트가 멀리 떨어져 있다면
"Prop Drilling" 이 발생한다.
Prop Drilling
은 props를 오로지 하위 컴포넌트로 전달하는 용도로만 쓰이는 컴포넌트들을 거치면서
React Component 트리의 한 부분에서 다른 부분으로 데이터를 전달하는 과정이다.
이것이 큰 문제가 되는 것은 아니지만, 트리가 깊어질수록 props를 추적하기 힘들고, 유지보수가 어려워질 수 있다.
그래서 나온 것들이 전역으로 상태를 관리하는 Redux, Mobx, Recoil 등이 있으며
React 자체에서는 Context API를 통해 전역으로 상태를 관리할 수 있다.
2. createContext
import { createContext } from 'react';
export const LevelContext = createContext(1);
먼저 context를 만들어준다. 필요한 컴포넌트에서 import해야하니 export문을 적어준다.
createContext의 인자로 default value를 넘겨준다.
3. useContext
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
export default function Heading({ children }) {
const level = useContext(LevelContext);
// ...
}
context를 사용할 컴포넌트에서 위에서 만든 context를 가져와서 전역 상태를 읽어온다.
useContext는 Hook이므로 react component 내에서만 호출할 수 있다.
4. Provider
App.js
import Heading from './Heading.js';
import Section from './Section.js';
export default function Page() {
return (
<Section level={1}>
<Heading>Title</Heading>
<Section level={2}>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Heading>Heading</Heading>
<Section level={3}>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Heading>Sub-heading</Heading>
<Section level={4}>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
<Heading>Sub-sub-heading</Heading>
</Section>
</Section>
</Section>
</Section>
Section.js
import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
return (
<section className="section">
<LevelContext.Provider value={level}>
{children}
</LevelContext.Provider>
</section>
);
}
위에서 Heading 컴포넌트에서 context 값을 읽어왔다.
react component 트리구조상 Section 컴포넌트가 Heading의 부모이므로,
Section내에서 Provider로 감싸준 후, props로 받은 level을 value로 설정해준다.
'Frontend > React' 카테고리의 다른 글
[React] React Query 톺아보기 (0) | 2023.07.25 |
---|---|
[React] Styledcomponents S-dot naming (2) | 2023.07.05 |
[React] Typescript + Inline style (1) | 2023.07.05 |
[React] React Router Dom V6.4 (0) | 2023.05.19 |
[React] CSS Reset (2) | 2023.01.08 |