| 일 | 월 | 화 | 수 | 목 | 금 | 토 | 
|---|---|---|---|---|---|---|
| 1 | ||||||
| 2 | 3 | 4 | 5 | 6 | 7 | 8 | 
| 9 | 10 | 11 | 12 | 13 | 14 | 15 | 
| 16 | 17 | 18 | 19 | 20 | 21 | 22 | 
| 23 | 24 | 25 | 26 | 27 | 28 | 29 | 
| 30 | 
- 군간
- 최대우도법
- ios
- f비
- pintos
- 평균로그우도
- Android
- 일반화오차
- qq플롯
- 자바
- 개발
- Java
- 상대 엔트로피
- 행렬
- 알고리즘
- 파스칼삼각형
- 군내
- Flutter
- 조건부정리
- 운영체제
- 선형대수학
- 비둘기집원리
- 잔차
- 개발자
- 앱개발
- Eigenvector
- Eigenvalue
- 앱
- AIC
- 논리회로 #컴퓨터
- Today
- Total
Dev_bob
[React] createContext/Context 본문
createContext는 component가 제공하거나 읽을 수 있는 context를 제공합니다.
const SomeContext = createContext(defaultValue)
context란 무엇인가?
context의 유용성을 설명하기 전에 props drilling에 대해서 알아봅시다.
props drilling이란?

props(매개변수)가 부모/자식 간의 관계에 있어서 props가 부모에서 부터~ 필요한 자식까지 계속해서 전달되는 것입니다.
이것은 공식문서에서는 'verbose'라고 표현하는데요, 쉽게 말하면 그냥 존나 복잡해진다는 겁니다. 왜냐하면 맨 하위의 자식 컴포넌트에서 필요한 정보를 부모노드가 갖고있다면 하나하나 다 전달해줘야하는 상황이 발생하니까요.
이를 대체하기 위한것이 오늘 우리가 이용할 Context입니다.
Context는 자신의 하위 컴포넌트, 즉 자식 컴포넌트들에게 데이터를 제공합니다. without passing props로요.
Context라는 것은, 다시말해 자식component에게 'ask'하는 방법을 알려주는 겁니다.
자식은 없지만, 부모는 갖고있는 정보를 부모에게 '요청' 할 수 있게 해준다는 것이지요.

자, 그러면 Context를 사용하는 방법을 알아볼까요?
1. Create Context
2. Use Context
3. Provide Context
이 세가지를 따르셔야합니다.

차근차근 해봅시다.
1. Create Context
import { createContext } from 'react';
export const LevelContext = createContext(1);
'react'라이브러리로부터 createContext라는 함수를 가져옵니다.
export를 하는 이유는 나중에 자식 컴포넌트가 요청을 보낼 때 어디서라도 호출이 가능하게끔하기 위해서 입니다.
2. Use Context
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';
react라이브러리로 부터 useContext 함수를 가져옵니다.
아까 상위 컴포넌트에서 생성했던 LevelContext도 불러와야겠죠?
그니까 현재상황은 부모 Component에서 CreateContext를 했고,
자식 component에서 useContext를 통해 정보를 불러오려고 시도하는겁니다.
(context 를 사용하지 않았을 때.. ☠️)
export default function Heading({ level, children }) {
  // ...
}
(context를 사용했을 때 😎)
export default function Heading({ children }) {
  const level = useContext(LevelContext);
  // ...
}useContext를 사용함으로써 props가 아니라, 함수 내부에서 호출하여 정보를 얻을 수 있게 되었습니다.
useContext를 사용하게 되면, React에게 호출한 컴포넌트(Heading component)가 LevelContext를 읽고싶다라고 전달하게 되는겁니다.
그러나~! 아직까진 정보전달이 안됩니다. ProvideContext를 안했으니까요 ㄱㄷㄱㄷ
3. Provide Context
import { LevelContext } from './LevelContext.js';
export default function Section({ level, children }) {
  return (
    <section className="section">
      <LevelContext.Provider value={level}>
        {children}
      </LevelContext.Provider>
    </section>
  );
}
section component는 children을 rendering 합니다.
이때 section component내부에 <LevelContext.Provider > 가 있는데, 이는 하위 컴포넌트에서 useContext를 통해 props없이 level이라는 데이터 값을 사용할 수 있게 합니다.
createContext 추가정보
createContext는 Context 객체를 반환합니다.
default값은 지정하지 않았다면, null이며, 특정한 값을 지정한다면 Provider를 사용하지 않고 useContext를 호출했을 때 default값을 반환합니다.
const ThemeContext = createContext('light'); // 기본값: 'light'
const AuthContext = createContext(null);    // 기본값: null
context는 보통 파일로 분리해서 사용합니다.
여러 파일에서 동일한 Context를 사용해야하는 경우, Context를 별도의 파일로 선언하는 것이 일반적입니다.
사용 예시
Contexts.js
import { createContext } from 'react';
export const ThemeContext = createContext('light');
export const AuthContext = createContext(null);
Button.js
import { ThemeContext } from './Contexts.js';
function Button() {
  const theme = useContext(ThemeContext);
  // ...
}
주의 사항!!
Context는 편리하지만 너무 많이 사용하면 복잡합니다.
props를 사용하는 장점은, 데이터 흐름을 명확하게 만들어줍니다. 유지보수 측면에서는 유용할 수 있습니다.
본 글은 공식문서를 참고하여 작성되었습니다.
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
https://react.dev/reference/react/createContext#provider
createContext – React
The library for web and native user interfaces
react.dev