본문 바로가기
728x90
반응형

Redux3

[redux + ts] dispatch, selector의 인자 타입 커스텀 훅으로 생성하기(매번 타입 선언을 하지 않아도 된다!) redux의 dispatch와 selector를 사용할 때, 타입스크립트가 적용된 경우 매번 타입을 선언해줘야하는 번거로움이 있다. 이러한 번거로움을 최소화하기 위해 커스텀 훅을 생성할 수 있다. /* store.ts */ export type RootState = ReturnType; export type AppDispatch = typeof store.dispatch; /* hook.ts */ import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'; import type { RootState, AppDispatch } from './store'; export const useAppDispatch: () => AppDis.. 2023. 3. 21.
[Redux] Redux-toolkit 사용법(완전 쉬움) Redux-toolkit은 완전 구세주이다. 갓!!! 전역에서 사용해야 하는 state를 사용할 때 사용하기에 아주 완벽하다. 굳이 미리 공부할 필요는 없고, props로 주고 받는 관계에 대해 지치고, 너무 불편함을 느끼고 있다면 이제는 공부해야할 때라고 생각한다. 등장 이유 1. react-redux는 설정해야할 것이 너무 많았기 때문에(1번이라도 사용해본 사람은 알거다..) 2. 미들웨어 사용 시 설치해야할 것이 너무 많았기 때문에 3. 반복되는 코드 작성을 줄이기 위해 4. 불변성을 유지하기 어려웠기 때문에(이전에는 spread 연산자를 사용하여 복제 후 사용했다.) 설치 방법 위와 같은 이유로 redux-toolkit이 등장하게 되었다. npm install @reduxjs/toolkit 사용방.. 2023. 3. 8.
[Redux] redux-toolkit state 초기화하는 방법 state를 초기화시키는 액션이 자주 사용되어 정리를 해두려고 한다. reducers의 액션이 () => initialState 할 수 있도록 코드를 작성해주면 된다. import { createSlice } from '@reduxjs/toolkit'; interface IInitialState { array: [category: string, type: string]; } const initialState: IInitialState = { array: ['', ''], }; export const selectSlice = createSlice({ name: 'select', initialState: initialState, reducers: { reset: () => initialState, }, }).. 2023. 2. 21.
728x90
반응형