기본적으로 리액트에서는 지역적으로 상태를 관리하며
다른 컴포넌트로 상태를 넘겨줄 때 props를 사용할 수 있다
하지만 컴포넌트가 복잡해짐에 따라
상속되는 경로가 길어지면서 상태의 관리가 복잡해질 수 있기 때문에
reducer hook을 통해 상태를 전역으로 선언하고 관리할 수 있다
하지만 전역으로 상태를 관리하는 것은 필요한 경우에만 사용하는 것이 권장된다
Redux와 Context API는 모두 상태 관리 도구로 활용할 수 있으나
Redux는 자바스크립트 라이브러리로 상태 관리를 가능하게 해주는 반면
Context 자체로는 상태관리 도구의 기능을 하지 않으며,
useState나 useReducer와 함께 사용했을 때 상태 관리를 할 수 있다
⚠️ Context API를 사용하면 컴포넌트의 재사용이 어려워지고
⚠️ 코드의 복잡성이 증가하기 때문에 꼭 필요한 경우에 사용해야 한다
context.js 파일 생성
createContext import, 생성, export하기
(provider에서 값을 제공한다면, 초기값을 넣지 않아도 된다)
//context.js
import { createContext } from "react";
export const tempContext = createContext(초기값);
Providing Context
ContextName.Provider 컴포넌트로 모든 자식에게
ContextName 에 해당하는 context를 제공할 수 있다
이 때, value 라는 이름의 prop으로만 context를 넘겨줄 수 있다
Provider에서 초기값을 제공하기 때문에
createContext에서 초기값을 넣지 않아도 된다
//App.js
import React from "react";
import { ThemeContext, UserContext } from './context'
export default function App() {
return (
<ThemeContext.Provider value="light">
<UserContext.Provider value={{ name: "Lee" }}>
<MyComponent />
</UserContext.Provider>
</ThemeContext.Provider>
);
}
MyComponent는 ThemeContext와 UserContext의 prop을 받을 수 있다
Consuming Context
context를 consuming하는(값을 읽는) 방법은 크게 두 가지로,
ContextName.consumer를 활용하는 방법과
useContext를 활용하는 방법이 있다
useContext로 context값 불러오기
//MyComponent.js
import { useContext } from "react";
import { ThemeContext, UserContext } from "./context";
const THEMES = {
light: {
backgroudColor: "#EEEEEE",
color: "black",
},
dark: {
backgroundColor: "#333333",
color: "white",
},
};
function MyComponent() {
const themeType = useContext(ThemeContext);
const { name } = useContext(UserContext);
// Layout과 Title은 styled components이다
return (
<Layout
backgroudColor={THEMES[themeType].backgroundColor}
color={THEMES[themeType].color}
>
<Title>{`환영합니다 ${name}님!`}</Title>
</Layout>
);
}
const [state, dispatch] = useReducer(reducer, initialState);
⚠️ context값 업데이트하는 부분 노션 다시보기
수업 노션:
https://www.notion.so/wecode/React-c32de005bf344cb4a85a28c059b60b2a