Redux
는 Javascript App을 위한 State Container
이다. Redux
는 일관성있고 예측 가능하게 동작하고 클라이언트나 서버에서 실행되며 테스트하기 쉬운 애플리케이션을 작성할 수 있게 도와준다. 그리고 중앙집중화로 취소와 재실행, 상태 지속 등과 같은 기능을 사용할 수 있다. 예를 들어 내 정보를 State에 한 번 저장하면 메인 페이지에서 사용할 수 있고 마이 페이지에서도 사용할 수 있게 해준다. 또한 디버깅이 가능해서 언제, 어디서, 왜 그리고 어떻게 State가 변경되었는지 추적할 수 있다. 주로 React
와 함께 사용한다.
reducer
를 통해 값이 변경되고 store
에서 가져온다.state
를 가지고 있는 곳이다. reducer
를 통해 변경된 state
를 받고 저장하는 곳이다.state
를 변경하는 곳이다. dispatch
를 통해 action
을 전달받고 그에 따른 작업을 수행한다. store
에 있는 이전의 state
를 받을 수 있다.다음과 같은 명령어로 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
를 보면 state
와 action
을 매개변수로 받는다. 처음 실행하면 state
에는 아무 값도 없기 때문에 초기값을 설정해준다. state
는 store
에 저장되어 있는 이전 state
이고 action
은 dispatch
를 통해 받은 action
이다. 그리고 action
에 type
을 통해 어떤 작업을 수행할지 정한다. 위의 예제 같은 경우 type
이 counter/incremented
라면 state.value
값이 1 증가하게 된다. 그리고 이렇게 만들어진 reducer
를 가지고 store
를 만든다. reducer
에서 반환한 state
는 store
가 가지게 된다.
subscribe
는 구독이라는 의미로 해당 store
에서 state
의 값이 변경되었을 때 실행되는 함수이다. 위의 예제에서 dispatch
를 통해 action
을 전달받은 reducer
가 state
를 변경시켰다면 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 }
먼저 폴더를 생성하고 다음 명령어를 통해 package.json
을 만들어준다.
# npm
npm init -y
# yarn
yarn init -y
그리고 CRA
를 통해 React
를 생성하고 사용할 패키지들을 설치한다.