[redux] middleware

Jin·2022년 1월 25일
0

redux

목록 보기
1/1
post-thumbnail

1. 미들웨어란?

액션이 디스패치 되어 리듀서에서 이를 처리하기 전에 사전에 지정된 작업들을 설정한다. 즉,액션과 리듀서 사이의 중간자로가 이해하면 쉽다.
리듀서가 액션을 처리하기전, 미들웨어가 할 수있는 작업들이 여러가지가 있다. 전달받은 액션을 기록 할 수도 있고, 전달 받은 액션에 기반해 액션을 아예 취소시킬수도있고, 다른 종류의 액션들을 추가적으로 실행 할 수도 있다.

미들웨어를 직접 만들어서 사용을 해도 되지만 보통 다른 프로그래머들이 만들어놓은 미들웨어를 사용한다. 대표적인 미들웨어들을 알아보자.

2. redux-logger

리듀서가 실행 되기 전과 실행된 후 그리고 어떤 액션이 실행되었는지를 편리하게 확인 할 수 있다.

2-1. 설치하기

$ yarn add redux-logger 혹은 npm i --save redux-logger

2-2. 사용 방법

import { applyMiddleware, createStore} from 'redux';
import logger from 'redux-logger'

cost store= createStore(reducer, applyMiddleware(logger));
// 혹은 커스텀 옵션을 지정해 줄 수 있다.

const logger = createLogger({
  // ...options
});

const store= createStore(reducer, applyMiddlewareI(logger));

출처 및 옵션 참고: https://github.com/LogRocket/redux-logger

3. redux-thunk

리덕스를 사용하는 어플리케이션에서 비동기 작업을 처리 할때 가장 기본적인 방법으로 redux-thunk를 사용하는것이다.

3-1. 설치하기

$ npm install redux-thunk 혹은 $yarn add redux-thunk

3-2. 사용방법

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

const store = createStore(rootReducer, applyMiddleware(thunk))

3-3. thunk란?

thunk는 평가를 지연시키기 위해 표현들을 감싼 함수이다.

// calculation of 1 + 2 is immediate
// x === 3
let x = 1 + 2

// calculation of 1 + 2 is delayed
// foo can be called later to perform the calculation
// foo is a thunk
let foo = () => 1 + 2

3-4. redux-thunk의 역할

redux-thunk는 객체 대신 함수를 생성하는 액션 생성함수를 작성 할 수 있게 해준다. redux에서는 기본적으로 액션 객체를 디스패치한다. redux-thunk는 액션의 디스패치를 지연시킬수도 있고, 특정 조건과 일치할때만 디스패치를 할 수도 있다.

액션이 1초 뒤에 디스패치 되는 경우

const INCREMENT_COUNTER = 'INCREMENT_COUNTER'

function increment() {
  return {
    type: INCREMENT_COUNTER
  }
}

function incrementAsync() {
  return dispatch => {
    setTimeout(() => {
      // Yay! Can invoke sync or async actions with `dispatch`
      dispatch(increment())
    }, 1000)
  }
}

특정 조건에서만 액션을 디스패치를 실행

function incrementIfOdd() {
  return (dispatch, getState) => {
    const { counter } = getState()

    if (counter % 2 === 0) {
      return
    }

    dispatch(increment())
  }
}

만약 리턴한수는 함수에서 dispatch, getState 를 파라미터로 받게 하면 스토어의 상태에도 접근이 가능하다. 따라서, 현재 스토어 상태 값에 따라 액션이 dispatch 될지 말지 정해줄 수도 있다.

따라서 보통 액션생성자는 그냥 하나의 액션객체를 생성할 뿐이지 redux-thunk는 그 내부에서 여러가지 작업을 할 수 있다.

4. redux-saga

redux-saga는 비동기작업처럼, 리듀서에서 처리하면 안되는 순수하지 않은 작업들을 하기 위한 리덕스 미들웨어이다.
redux-thunk 경우 함수를 dispatch 해줬다면, redux-saga에서는 일반 액션을 dispatch하게 된다.
그리고 특정 액션이 발생하면 이를 모니터릴 하여 이에 기반한 추가적인 작업을 하도록 설계한다.
redux-saga에서는 Generator를 사용하여 function문법을 사용한다.

4-1. 설치하기

$ yarn add redux-saga 혹은 $ npm i --save redux-saga

4-2. 사용 방법

mport { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import modules from'./modules';
const logger = createLogger();

const sagaMiddleware = createSagaMiddleware();

const store = createStore(modules, applyMiddleware(sagaMiddleware));

export default store;
profile
내가 다시 볼려고 작성하는 블로그. 아직 열심히 공부중입니다 잘못된 내용이 있으면 댓글로 지적 부탁드립니다.

0개의 댓글