context: 맥락
React에서 제공하는 Context API는 말그대로 한 컴포넌트가 어떤 맥락에 포함되는 것이라고 말할 수 있다.
useState를 사용해 상태를 관리할 때, 그 상태를 자식 컴포넌트에 전달하면, 그 깊이가 깊어질 때 props drilling이 일어나 불편한 상황이 되어버린다.
그런 props drilling 문제를 해결하기 위해 React에서 Context API를 제공한다.
import { createContext, useContext } from 'react';
const MyContext = createContext(null);
export default function MyApp() {
return (
<MyContext.Provider value={2}>
<MyComponent />
</MyContext.Provider>
)
}
function MyComponent() {
const myNum = useContext(CountContext);
return (
<div>{myNum}</div> // 2
)
}
위의 코드처럼, Context Provider 내부에 있는 컴포넌트는 Provider의 value 속성으로 전달된 값을 사용할 수 있다.
이 value 속성은 컴포넌트가 여러 겹으로 깊어져도 가장 안쪽에 있는 자손 컴포넌트까지 모두 사용할 수 있기 때문에 props drilling의 불편함을 겪지 않을 수 있다.
이렇게 큰 범위에서 state도 관리할 수 있다.
App 전체를 감싸는 Provider를 만든다면 전역의 상태도 쉽게 관리할 수 있다는 것이다.
(App 전체에서 필요한 user 정보 같은 상태를 관리할 때 유용함)
import React, { createContext, useContext, useState } from "react";
// 1. Context 생성
const CounterContext = createContext();
// 2. Provider 컴포넌트
const CounterProvider = ({ children }) => {
const [count, setCount] = useState(0);
// Context Provider를 미리 생성
return (
<CounterContext.Provider value={{ count, setCount }}>
{children}
</CounterContext.Provider>
);
};
// 3. 사용 예시
const Counter = () => {
const { count, setCount } = useContext(CounterContext);
return (
<div>
<h1>카운트: {count}</h1>
<button onClick={() => setCount(count + 1)}>+1</button>
</div>
);
};
// 4. App 컴포넌트에서 Provider로 감싸기
const App = () => (
<CounterProvider>
<Counter />
</CounterProvider>
);
export default App;
이렇게 Context Provider의 value 속성을 통해 setState 함수를 전달하면, 해당 Provider 내에서만 사용할 상태 변수를 쉽게 관리할 수 있다!