티스토리 뷰

Language/TypeScript

React에서 TypeScript 사용2 - redux

공부하는 승승 2023. 7. 3. 11:42

- React에서 Redux 사용 이유

  1. 모든 컴포넌트가 state를 공유할 수 있음
  2. 수정 방법을 파일 한 곳에 정의 해둠

=> 버그 추적이 용이함

 

타입지정은

  • state 초기값 타입 지정
  • reducer 안의 action 파라미터의 타입 지정
  • 나머지는 타입 지정 필요x (자동임) 

 

<index.tsx>

/* 버튼을 누르면 state에 +1 해주는 예제 */
import { Provider } from 'react-redux';
import { createStore } from 'redux';

interface Counter {
    count: number;
}

const initialState: Counter = { count: 0 };

function reducer(state = initialState, action: { type: string }) {
    if (action.type === '증가') {
        return { ...state, count: state.count + 1 };
    } else if (action.type === '감소') {
        return { ...state, count: state.count - 1 };
    } else {
        return initialState;
    }
}

const store = createStore(reducer);

// store의 타입 미리 export 해두기
export type RootState = ReturnType<typeof store.getState>; // store 타입이 자동으로 나옴

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>
    </React.StrictMode>,
    document.getElementById('root'),
);

 

<App.tsx>

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Dispatch } from 'redux';
import { RootState } from './index'; // store 타입 지정해둔거

function App() {
    const 꺼내온거 = useSelector((state: RootState) => state);
    const dispatch: Dispatch = useDispatch();

    return (
        <div className="App">
            {꺼내온거.count}
            <button
                onClick={() => {
                    dispatch({ type: '증가' });
                }}>
                버튼
            </button>
            <Profile name="kim"></Profile>
        </div>
    );
}

 

 

- @reduxjs/toolkit 라이브러리를 설치하면 코드가 더 깔끔해짐

- 장점

  1. 함수라서 보기 좋음
  2. state 수정 시 사본만들 필요가 없음

- slice: state + reducer

 

<index.tsx>

import { createSlice, configureStore, PayloadAction } from '@reduxjs/toolkit';
import { Provider } from 'react-redux';

interface Counter {
    count: number;
}

const initialState: Counter = { count: 0, user : 'kim' };

const counterSlice = createSlice({
  name: 'counter',
  initialState : initialState,
  reducers: {
    증가 (state){
      state.count += 1
    },
    감소 (state){
      state.count -= 1
    },
    양만큼증가 (state, action :PayloadAction<number>){ // action: dispatch() 할 때 넣는 파라미터와 같은 타입
      state.count += action.payload
    }
  }
})

let store = configureStore({
  reducer: {
    counter1 : counterSlice.reducer
  }
})

//state 타입을 export 해두는건데 나중에 쓸 데가 있음
export type RootState = ReturnType<typeof store.getState>

//수정방법 만든거 export
export let {증가, 감소, 양만큼증가} = counterSlice.actions

<App.tsx>

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Dispatch } from 'redux';
import { RootState, 증가 } from './index'; // store 타입 지정해둔거

function App() {
    const 꺼내온거 = useSelector((state: RootState) => state);
    const dispatch: Dispatch = useDispatch();

    return (
        <div className="App">
            {꺼내온거.count}
            <button
                onClick={() => {
                    dispatch(증가()); // reduxjs.toolkit 방식
                }}>
                버튼
            </button>
            <Profile name="kim"></Profile>
        </div>
    );
}

'Language > TypeScript' 카테고리의 다른 글

[TypeScript] Literal Types  (0) 2023.07.11
[TypeScript] type 키워드, object readonly  (0) 2023.07.11
React에서 TypeScript 사용  (0) 2023.07.03
[TypeScript] 타입 확정 Narrowing & Assertion  (0) 2023.06.29
[TypeScript] 함수 타입  (0) 2023.06.29
댓글