Javascript/React

[React] redux-thunk

dev23 2024. 5. 14. 17:54
반응형

redux-thunk

- 리덕스 사용 프로젝트에서 비동기 작업을 처리할 때 가장 기본적으로 사용하는 미들웨어


* thunk

- thunk는 특정 작업을 나중에 할 수 있도록 미루기 위해 함수 형태로 감싼 것을 의미함.

const addOne = x => x + 1;

const addOneThunk = x => () => addOne(x);

const fn = addOneThunk(1);

setTimeout(() => {
    const value = fn(); // fn이 실행되는 시점에 연산
    console.log(value);
}, 1000);

 

redux-thunk 함수 예시

const sampleThunk = () => (dispatch, getState) => {
    // 현재 상태를 참조할 수 있고,
    // 새 액션을 디스패치할 수도 있다.
}

 

redux-thunk 미들웨어 적용

- redux-thunk 패키지를 먼저 설치한 후 적용한다.

1. 패키지설치

$ yarn add redux-thunk

 

2. 적용(src/index.js)

import { thunk } from 'redux-thunk';

const logger = createLogger();
const store = createStore(rootReducer, applyMiddleware(logger, thunk));

 

thunk 생성 함수

- redux-thunk는 액션 생성 함수에서 일반 액션 객체를 반환하는 대신에 함수를 반환한다.

const increase = createAction(INCREASE);
const decrease = createAction(DECREASE);

export const increaseAsync = () => dispatch => {
    setTimeout(() => {
    	dispatch(increase());
    }, 1000);
};

export const decreaseAsync = () => dispatch => {
    setTimeout(() => {
    	dispatch(decrease());
    }, 1000);
};



반응형