본문 바로가기
개발일지/redux

TypeScript-React에서 ReduxToolkit 사용해보기

by 한삐 2023. 1. 18.
728x90

React TypeScript에서 ReduxToolkit을 사용하기 위해 간단한 설정만 기록합니다.

 

javaScript에서 ReduxToolkit 사용하는법은 아래 링크의 예제를 참고해보셔도 좋습니다.

https://hanbbistory.tistory.com/53

 

React에서 reduxtoolkit 사용해보기 .with AsyncThunk

// redux/modules/postSlice.js import { createAsyncThunk,createSlice } from "@reduxjs/toolkit"; const initialState = { // 초기값, data, isLoading, error로 상태관리 posts: [], isLoading: false, error: null, }; const postsSlice = createSlice({ name:"p

hanbbistory.tistory.com

 

1. store 설정

state와 dispatch type을 가져와준다.

// store.ts
import { configureStore } from "@reduxjs/toolkit";
import commentSlice from "./commentSlice";

const store = configureStore({
  reducer: {
    commentSlice,
  },
});
export default store;

export type RootState = ReturnType<typeof store.getState>; // 1. state type 가져오기
export type AppDispatch = typeof store.dispatch; // 2. dispatch type 가져오기

 

2. redux hook 설정해주기

dispatch 함수와 useSelector 실행을 위해, redux hook을 따로 설정해준다.

// useRedux.ts

import { useDispatch, useSelector } from "react-redux";
import type { TypedUseSelectorHook } from "react-redux";
import type { RootState, AppDispatch } from "../redux/store"; // store에서 미리 설정해준 state와 dispatch type

export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

 

위의 설정을 마치면 js에서 dispatch를 사용하는 것과 같이 사용할 수 있다.

// Form.tsx
import { useAppDispatch, useAppSelector } from "../hook/useRedux";
import { FormEvent } from "../type"; // 별도로 지정한 eventType
import { addComments } from "../redux/commentSlice"; // Slice의 action함수

export const Form = () => {
	const dispatch = useAppDispatch();
    
    const formData = {...}
    
    const onSubmitHandler = async (e: FormEvent, dispatch: any) => {
        e.preventDefault();
        dispatch(addComments(formData)); // 정상작동
    };

    return ( ...
}

 


참고문서

https://redux-toolkit.js.org/usage/usage-with-typescript

 

Usage With TypeScript | Redux Toolkit

 

redux-toolkit.js.org

 

728x90

댓글