Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- next.js
- 블로그만들기
- 투포인터
- JavaScript
- tailwindcss
- 그리디
- 슬라이딩윈도우
- 라이프사이클
- nestjs
- nextjs
- 버블정렬
- 스택
- react-query
- js알고리즘
- cookie
- never타입
- typscript
- 빅오
- textarea autosize
- NextAuth
- TypeScript
- styled-components
- isNaN
- 정렬
- react
- Algorithm
- 큐
- aws lightsail
- 알고리즘
- 해쉬
Archives
- Today
- Total
far
Redux Toolkit 세팅하기 본문
Redux Toolkit을 처음 사용하면서 잊어버리지 않기 위해 기록.
npm i @reduxjs/toolkit react-redux
redux-toolkit 설치
// pages/_app.tsx
function MyApp({ Component, pageProps }: AppProps) {
return (
<div className="App">
<Provider store={store}>
<Component {...pageProps} />
</Provider>
</div>
);
}
export default MyApp;
Provider에 store를 넣어준다 (아래의 코드를 인식하기 위해)
// store/config.ts
const rootReducer = combineReducers({
// 리듀서를 여기에 추가해준다.
});
export const store = configureStore({
reducer: rootReducer,
devTools: process.env.NODE_ENV !== 'production',
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
export const useAppDispatch = () => useDispatch<AppDispatch>();
export default store;
Redux에서 reducers파일 만들고 설정하던 부분(rootReducer)이 여기에 선언된다.
매번 useSelector를 불러올 때 마다 Typescript를 설정 해줘야하는 걸 묶어 useAppSelector로 설정해준다.
useDispatch도 비슷한 개념.
// slices/userSlice.ts
import { createSlice, PayloadAction } from '@reduxjs/toolkit';
interface IUser {
email: string;
password: string;
}
export interface IUserState {
value: IUser;
}
const initialState = {
value: {
email: '',
password: '',
} as IUser,
} as IUserState;
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
login: (state: IUserState, action: PayloadAction<IUser>) => {
state.value = action.payload;
},
logout: (state: IUserState) => {
state.value = initialState.value;
},
},
});
export const { login, logout } = userSlice.actions;
export default userSlice.reducer;
initialState에 최초 스테이트를 지정한다.
name은 유니크하게 짓고 각 Action에 따른 Reducer를 작성해준다. 그럼 createSlice가 Aciton과 Reducer를 만들어준다.
덕분에 Switch문에 하나하나씩 액션타입을 지정해주고 기존 state에 바뀐점을 적용해야 했던 작업이 사라졌다.
import { login } from '@slices/userSlice'
import { useAppSelector, useAppDispatch } from '@store/config'
const dispatch = useAppDispatch();
const request = useAppSelector((state) => state.user.value);
const onSubmit = useCallback((e: React.FormEvent<HTMLFormElement>) => {
...
dispatch(login({ email, password }));
}, [email, password]);
이런식으로 불러와서 사용하면 끝
'React > Redux' 카테고리의 다른 글
[React + Redux-toolkit] addCase cannot be called with two reducers for the same action type에러 (0) | 2023.02.07 |
---|---|
[React + Redux-toolkit + Next.js] Search구현을 위한 Reducer사용 (0) | 2023.01.21 |
Comments