Redux란

Redux는 Javascript App을 위한 State Container이다. Redux는 일관성있고 예측 가능하게 동작하고 클라이언트나 서버에서 실행되며 테스트하기 쉬운 애플리케이션을 작성할 수 있게 도와준다. 그리고 중앙집중화로 취소와 재실행, 상태 지속 등과 같은 기능을 사용할 수 있다. 예를 들어 내 정보를 State에 한 번 저장하면 메인 페이지에서 사용할 수 있고 마이 페이지에서도 사용할 수 있게 해준다. 또한 디버깅이 가능해서 언제, 어디서, 왜 그리고 어떻게 State가 변경되었는지 추적할 수 있다. 주로 React와 함께 사용한다.

설치

다음과 같은 명령어로 Redux를 프로젝트에 설치할 수 있다.

# npm
npm i redux

# yarn
yarn add redux

Redux는 배포용에서도 동작해야 하기 때문에 --save-dev 플래그를 사용하지 않는다.

예제

import { createStore } from "redux"

// Reducer
function counterReducer(state = { value = 0 }, action) {
	switch (action.type) {
    case 'counter/incremented':
      return { value: state.value + 1 }
    case 'counter/decremented':
      return { value: state.value - 1 }
    default:
      return state
  }
}

// Store
let store = createStore(counterReducer)

// Subscribe
store.subscribe(() => console.log(store.getState())

// Dispatch
store.dispatch({ type: "counter/incremented" })
// { value: 1 }
store.dispatch({ type: "counter/incremented" })
// { value: 2 }
store.dispatch({ type: "counter/decremented" })
// { value: 1 }

먼저, counterReducer를 보면 stateaction을 매개변수로 받는다. 처음 실행하면 state에는 아무 값도 없기 때문에 초기값을 설정해준다. statestore에 저장되어 있는 이전 state이고 actiondispatch를 통해 받은 action이다. 그리고 actiontype을 통해 어떤 작업을 수행할지 정한다. 위의 예제 같은 경우 typecounter/incremented라면 state.value 값이 1 증가하게 된다. 그리고 이렇게 만들어진 reducer를 가지고 store를 만든다. reducer에서 반환한 statestore가 가지게 된다.

subscribe는 구독이라는 의미로 해당 store에서 state의 값이 변경되었을 때 실행되는 함수이다. 위의 예제에서 dispatch를 통해 action을 전달받은 reducerstate를 변경시켰다면 state가 콘솔에 찍히게 된다.

또한 Toolkit을 통해 Redux를 만들 수 있다. Toolkit을 사용하면 코드가 좀더 직관적이고 보기 편하게 된다.

import { createSlice, configureStore } from "@reduxjs/toolkit"

// Reducer
const counterSlice = createSlice({
	name: "counter",
	initialState: {
		value: 0
	},
	reducers: {
		incremented: state => {
			state.value += 1
		},
		decremented: state => {
			state.value -= 1
		}
	}
})

export const { incremented, decremented } = counterSlice.actions

// Store
const store = configureStore({
	reducer: counterSlice.reducer
})

// Subscribe
store.subscribe(() => console.log(store.getState())

// Dispatch
store.dispatch(incremented())
// { value: 1 }
store.dispatch(incremented())
// { value: 2 }
store.dispatch(decremented())
// { value: 1 }

React와 함께 사용하기

먼저 폴더를 생성하고 다음 명령어를 통해 package.json을 만들어준다.

# npm
npm init -y

# yarn
yarn init -y

그리고 CRA를 통해 React를 생성하고 사용할 패키지들을 설치한다.