1. Context
const MyContext = React.createContext(defaultValue);
2. Prodiver
- 컴포넌트를 Provider로 감싸주면, 그 하위 모든 컴포넌트들이 Context에 있는 전역 데이터에 접근할 수 있음.
- value 속성을 지정해주어야 함.
- value 값이 바뀌면, Provider에 속해 있는 컴포넌트들이 모두 렌더링됨.
3. useContext
const UserContext = React.createContext();
const user = {count: 3};
<UserContext.Provider value={user}>
</UserContext.provider>
import { useContext } from 'react';
const user = useContext(UserContext);
- 자식 컴포넌트에서 데이터를 받아올 수 있음
- 이런 식으로 전역 변수를 불러올 수도, state를 불러올 수도, dispatch를 불러올 수도 있음
4. useReducer
const initialState = {count : 0};
const reducer = (state, action) =>{
switch (action.type)
...
}
const [state, dispatch] = useReducer(reducer, initialState);
- 선언하면, state와 dispatch가 만들어짐.
- state는 useState에서 사용하던 그 상태임
- dispatch는 reducer라는 로직을 지니고 있는 액션 실행 로직 함수임
- dispatch를 전역에서 사용할 수 있게 하려면(state 변경을 하위 컴포넌트에서 할 수 있게 하려면) Context로 생성해야 함
출처
https://velog.io/@secho/%EB%A6%AC%EC%95%A1%ED%8A%B8%EC%97%90%EC%84%9C%EC%9D%98-%EC%A0%84%EC%97%AD%EC%83%81%ED%83%9C%EA%B4%80%EB%A6%ACContext-API