redux-thunk

김민석·2021년 6월 3일
0

Redux

목록 보기
4/5

react 공식문서의 thunk 관련 내용
side-effect를 금지하는 것과 관련하여 thunk가 소개되는 부분임


내가 맞게 이해하고 있는 건지는 모르겠지만,
앞에서 middleware의 작동 원리에 대해서 어느 정도 공부하고 나니 , thunk의 원리도 간단한 것 같다는 생각이 들었다.

redux-thunk는 코드의 길이도 매우매우 짧다.

redux-thunk 코드

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => (next) => (action) => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

(ㄷㄷ....)

redux-thunk 사용 시 action creator의 형태

redux-thunk는 기존에 object type이 오던 action 자리에 함수가 오는 형태다.

// Write a function that has `dispatch` and `getState` as arguments
const actionCreator = (arg) => (dispatch, getState) => {
  // Make an async HTTP request
  client.get('todos').then(todos => {
    // Dispatch an action with the todos we received
    dispatch({ type: 'todos/todosLoaded', payload: todos })
    // Check the updated store state after dispatching
    const allTodos = getState().todos
    console.log('Number of todos after loading: ', allTodos.length)
  })
}

// Pass the _function_ we wrote to `dispatch`
store.dispatch(actionCreator(arg))
// logs: 'Number of todos after loading: ###'

즉, 여러 middleware를 통해 생성된 dispatch 함수의 인자로
action 객체가 함수 형태로 들어오면,
next를 통해 뒷 함수들로 흘리지 않고,
즉시 비동기 처리를 하여 dispatch를 진행시키는 형국으로 볼 수 있다.

0개의 댓글