React/react-redux
[Redux-Toolkit] Redux와 Redux Toolkit 사용법 비교하기
paintover23
2023. 9. 20. 15:21
728x90
항상 헷갈렸던 react-redux를 이번 기회에 복습해보았다. 대세로 자리잡은 react-redux-toolkit과 toolkit을 사용하지 않은 버전은 어떻게 다른지 비교해보고자 한다. 내용은 생화코딩 강좌의 리덕스편을 참고하였다.
[리덕스란?]
리덕스는 리액트와 가장 많이 사용되지만, 사실 자바스크립트 기반이기만 하면 사용할 수 있는 상태관리 라이브러리이다.
상태는 오로지 읽을 수만 있고, 상태를 변경하기 위해서는 액션(action)을 발생시켜야 한다.
[리덕스 툴킷이란?]
리덕스 툴킷은 리덕스에서 공식적으로 추천하는 helper 라이브러리이다.
redux-devtools, redux-thunk 등의 라이브러리가 미리 포함되어 있다.
먼저 코드로 다른점을 파악해보자.
[1. React-Redux]
// without redux-toolkit
import React from 'react';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
// reducer 정의
function reducer(state, action) {
if (action.type === 'up') {
return { ...state, value: state.value + action.step };
// 기존값을 복제
}
return state;
}
// 초기값 정의
const initialState = { value: 0 };
// state와 reducer를 store에 저장
const store = createStore(reducer, initialState);
// 컴포넌트
function Counter() {
// 액션을 전송하는 dispatch, 액션이 있는 곳에서 사용
const dispatch = useDispatch();
// useSelector는 함수를 인자로 받음
// dispatch는 액션을 받음(actiond은 필수, payload는 옵션)
const count = useSelector((state) => state.value);
return (
<div>
<button
onClick={() => {
dispatch({ type: 'up', step: 2 });
}}
>
+
</button>
{count}
</div>
);
}
// provider를 주입하여 store가 적용되는 영역 정의
export default function App() {
return (
<Provider store={store}>
<div>
<Counter></Counter>
</div>
</Provider>
);
}
[react-redux 특징]
- state를 변경하는 방법을 정의한 reducer 함수가 있다.
- reducer는 원본을 수정하면 안되고, 원본을 복사한 복제본을 사용한다.
- if... 분기 처리를 통해 액션 별로 나누어서 작성한다.
[2. React-Redux-Toolkit]
[react-redux 설치하기]
- npm install react-redux
[redux toolkit 설치하기]
- 현재 디렉토리에 최초 설치: npx create-react-app . --template redux -> 이 경우는 counter template 까지 다 만들어준다!
- 이미 app이 존재하는 경우 도입: `npm install @reduxjs/toolkit`
[참고사항]
- 모듈별로(store, slice, components..) 분리하여 관리하도록 한다.
[import 문 정리]
import { configureStore, createSlice } from '@reduxjs/toolkit';
import { Provider, useDispatch, useSelector } from 'react-redux';
[리덕스 툴킷을 활용한 셋팅 절차]
- slice 만들기(구성 = 이름, 초기값, reducer)
- slice를 store에 등록하기
- 컴포넌트에 dispatch(action을 받음), useSelector(상태를 store에서 꺼내오는 목적, 인자로 함수를 받음) 삽입하기
- App에 Provider 주입하기
// store.jsx
import { configureStore } from '@reduxjs/toolkit';
import counterSlice from './slice';
const store = configureStore({
reducer: {
counter: counterSlice.reducer,
},
});
export default store;
// slice.jsx
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
up: (state, action) => {
console.log('action', action); // payload, type으로 구성
state.value = state.value + action.payload;
},
},
});
console.log('counterSlice', counterSlice);
// actions, caseReducers, getInitialState, name, reducer..
export default counterSlice;
export const { up } = counterSlice.actions; // up
// app.jsx
import React from 'react';
import { createStore } from 'redux';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store.jsx';
import { up } from './slice.jsx';
// 컴포넌트
function Counter() {
// 액션을 전송하는 dispatch, 액션이 있는 곳에서 사용
const dispatch = useDispatch();
// useSelector: component에서 store에 있는 state 갖다 쓸 때 필요. 함수를 인자로 받음
// dispatch는 액션을 받음(action은 필수, payload는 옵션)
const count = useSelector((state) => state.counter.value);
console.log(state)
return (
<div>
<button
onClick={() => {
dispatch(up(2));
}}
>
+
</button>
{count}
</div>
);
}
// provider를 주입하여 store가 적용되는 영역 정의
export default function App() {
return (
<Provider store={store}>
<div>
<Counter></Counter>
</div>
</Provider>
);
}
[react-redux-toolkit 특징]
- 작은 store라고 할 수 있는 slice 가 있다. 이 slice를 store에 등록하는 과정이 필요하다.
- react-redux-toolkit을 사용하지 않았을 때 같이, 복제본을 만들 필요가 없다.
- 리덕스 툴킷은 action creater를 자동 생성해준다.
728x90
반응형