티스토리 뷰

redux-thunk

redux-thunk는 리덕스에서 비동기 작업을 처리할 때 가장 많이 사용하는 미들웨어.

이 미들웨어를 사용하면 액션 객체뿐만 아니라 함수도 디스패치 할 수 있음

import { useDispatch } from 'react-redux'

const dispatch = useDispatch()

// 기존
dispatch(Action객체)

// redux-thunk
dispatch(함수)

 

내부 구조

action이 함수면 함수의 인자로 dispatch와 getState 전달,

아니면 next(action객체) 호출

const thunk = store => next => action =>
  typeof action === 'function'
    ? action(store.dispatch, store.getState)
    : next(action)

 

사용 예시(Codestates cmarket-redux 과제 src/actions/index.js)

export const notify = (message, dismissTime = 5000) => dispatch => {
  const uuid = Math.random()
  dispatch(enqueueNotification(message, dismissTime, uuid))
  setTimeout(() => {
    dispatch(dequeueNotification())
  }, dismissTime)
}

 

사용 전 임포트(store.js 파일)

import { compose, createStore, applyMiddleware } from "redux";
import rootReducer from '../reducers/index';
import thunk from "redux-thunk";

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ 
  ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({})
  : compose;
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

export default store;

 

 

Redux Toolkit

Redux의 복잡한 구조, 기능 사용을 위한 많은 패키지 추가, 상용구 코드 작성 필요성의 불편함을 해소하기 위해 만들어진 패키지

설치

npx create-react-app my-app --template redux
// 혹은
npm install @reduxjs/toolkit

configureStore

createReducer

createAction

createSlice

createAsyncThunk 비동기

createEntityAdapter

 

 

 

 

참고

React-redux

redux-toolkit 공식문서

 

22.12.29

코스 S3U4

'코드스테이츠(SEB_FE_42)' 카테고리의 다른 글

[React] Redux Toolkit  (0) 2023.01.01
[사용자 친화 웹] 웹 표준  (0) 2022.12.30
[React] Redux  (0) 2022.12.28
[React] 상태 관리  (0) 2022.12.27
[React] storybook(CDD)  (2) 2022.12.23
댓글
공지사항