반응형
1. 리듀서 (Reducer)
- 이전 상태와 동작을 받아서 새 상태를 리턴함.
- 항상 현재 상태를 '읽기 전용'으로 다루며, 기존 상태를 변경하지 않고 새상태를 리턴.
- 메뉴Toggle , 로딩 On/Off , 테마Change 등.
2. Reducer 선언
//GlobalReducer.tsx
//TypeScript&Redux
import {ActionType, createAction, createReducer} from 'typesafe-actions'
//인터페이스 선언
export interface IGlobalReducer {
menuShow: boolean
}
//초기값 설정
const initialState: IGlobalReducer = {
menuShow: false
}
//액션 생성 함수
export const MENU_SHOW_TOGGLE = "global/MENU_SHOW_TOGGLE"
export const menuShowToggle = createAction(MENU_SHOW_TOGGLE)<boolean>();
export const actions = {menuShowToggle}
type GlobalReducerAction = ActionType<typeof actions>
// 리듀서 추가
const reducer = createReducer<IGlobalReducer, GlobalReducerAction>(initialState, {
[MENU_SHOW_TOGGLE]: (state) => {
return ({
...state
, menuShow: !state.menuShow
})
}
})
export default reducer
3. 리덕스(Redux)
- 상태 컨테이너
- 상태를 저장소에 보관함.
npm install react-redux
4. useSelector
- connext 함수를 이용하지 않고 리덕스의 state 를 조회할 수 있음.
import { useSelector } from 'react-redux';
import { RootState } from '../reducers';
const LoadingView = () => {
const {loading} = useSelector((state:RootState) => state.globalReducer)
return (
<>
{loading === false ? "" :
<>
<LoadingArea/>
</>
}
</>
)
}
export default LoadingView
4. useDispatch
- 만들어둔 액션 생성 함수를 import 함.
import {useDispatch, useSelector} from "react-redux";
import { RootState } from '../reducers';
const dispatch = useDispatch();
const { menuShow } = useSelector((state: RootState) => state.globalReducer);
const handleDrawerClose = () => {
dispatch({
type: MENU_SHOW_TOGGLE,
});
};
반응형
'React ( + Next.js )' 카테고리의 다른 글
[React] immer 사용하기 (0) | 2022.05.26 |
---|---|
[Nextjs] Hooks (0) | 2022.05.26 |
[React/Next.js] Recoil (0) | 2022.05.24 |
[PM2] PM2 사용하기 (0) | 2022.05.19 |
[Next.js] SSR(Server-Side-Rendering) vs SSG(Static-Site-Generation) (0) | 2022.04.27 |