Redux와 Redux Toolkit은 대표적인 상태 관리 라이브러리 중 하나다.
Redux는 상태 관리의 기본적인 원칙과 기능을 제공하며, Redux Toolkit은 Redux 사용을 더 쉽고 간결하게 만들어준다.
Redux는 JavaScript 애플리케이션의 상태를 중앙에서 관리하는 라이브러리로, 주로 React와 함께 사용된다. 상태의 일관성을 유지하고 복잡한 상태 전이를 관리하기에 적합하다.
import { createStore } from 'redux';
// 초기 상태 정의
const initialState = {
count: 0,
};
// 액션 생성자
const increment = () => ({ type: 'INCREMENT' });
const decrement = () => ({ type: 'DECREMENT' });
// 리듀서
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};
// 스토어 생성
const store = createStore(counterReducer);
// 구독
store.subscribe(() => console.log(store.getState()));
// 상태 변경
store.dispatch(increment()); // count: 1
store.dispatch(decrement()); // count: 0
Redux Toolkit은 Redux가 제공하는 공식 유틸리티 라이브러리로, Redux를 더 간편하게 설정하고 사용할 수 있도록 도와준다.
createSlice로 액션과 리듀서를 통합하여 작성할 수 있다.createAsyncThunk로 비동기 작업을 간소화할 수 있다.configureStore를 사용하여 스토어를 생성한다.import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useDispatch, useSelector } from 'react-redux';
// Slice 생성
const counterSlice = createSlice({
name: 'counter',
initialState: { count: 0 },
reducers: {
increment: (state) => {
state.count += 1; // Immer를 사용하여 불변성 자동 관리
},
decrement: (state) => {
state.count -= 1;
},
},
});
// 액션과 리듀서 추출
const { increment, decrement } = counterSlice.actions;
const counterReducer = counterSlice.reducer;
// 스토어 생성
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
// 컴포넌트
const Counter = () => {
const count = useSelector((state) => state.counter.count);
const dispatch = useDispatch();
return (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
);
};
// 앱
const App = () => (
<Provider store={store}>
<Counter />
</Provider>
);
export default App;
createAsyncThunconfigureStore