전역 상태 관리를 위한 Context API
2023. 11. 16. 23:09ㆍ개발 문서/React
728x90
반응형
React의 Context API는 전역 상태를 관리하기 위한 강력한 도구로, 컴포넌트 트리 전체에서 데이터를 공유할 수 있습니다. Context를 사용하면 중첩된 여러 컴포넌트 간에 데이터를 손쉽게 전달할 수 있습니다.
아래는 Context API를 사용한 간단한 예제입니다.
1. Context 생성:
// MyContext.js
import { createContext, useContext, useState } from 'react';
const MyContext = createContext();
const MyContextProvider = ({ children }) => {
const [globalState, setGlobalState] = useState('');
const updateGlobalState = (newState) => {
setGlobalState(newState);
};
return (
<MyContext.Provider value={{ globalState, updateGlobalState }}>
{children}
</MyContext.Provider>
);
};
const useMyContext = () => {
return useContext(MyContext);
};
export { MyContextProvider, useMyContext };
위의 코드에서 MyContextProvider
컴포넌트는 Context를 제공하는 역할을 합니다. useMyContext
훅을 사용하여 컴포넌트에서 해당 Context의 값을 읽을 수 있습니다.
2. Context 제공:
// App.js
import React from 'react';
import { MyContextProvider } from './MyContext';
import ChildComponent from './ChildComponent';
const App = () => {
return (
<MyContextProvider>
<div>
<h1>My App</h1>
<ChildComponent />
</div>
</MyContextProvider>
);
};
export default App;
3. Context 사용:
// ChildComponent.js
import React from 'react';
import { useMyContext } from './MyContext';
const ChildComponent = () => {
const { globalState, updateGlobalState } = useMyContext();
return (
<div>
<p>Global State: {globalState}</p>
<button onClick={() => updateGlobalState('New Global State')}>
Update Global State
</button>
</div>
);
};
export default ChildComponent;
위의 코드에서 ChildComponent
는 MyContext
를 사용하여 전역 상태를 읽고 업데이트합니다.
이러한 방식으로, MyContextProvider
로 감싼 컴포넌트 트리 내에서 어디서든 useMyContext
훅을 사용하여 전역 상태를 읽고 업데이트할 수 있습니다. Context API를 사용하면 Redux나 MobX와 같은 상태 관리 라이브러리 없이도 간단한 애플리케이션 상태를 전역으로 관리할 수 있습니다.
'개발 문서 > React' 카테고리의 다른 글
액션, 리듀서, 스토어의 역할 및 기본 상태 관리 (0) | 2023.11.16 |
---|---|
라우팅 및 동적 라우팅의 개념 (0) | 2023.11.16 |
useState와 useEffect의 기본 활용 (0) | 2023.11.16 |
삼항 연산자를 사용한 조건부 렌더링 및 동적 리스트 생성 (0) | 2023.11.16 |
React에서의 이벤트 처리 방법 (0) | 2023.11.15 |