이 애플리케이션은 컴포넌트3, 컴포넌트6에서만 사용되는 상태입니다. 이런 상태는 다소 비효율적이다.
Redux를 사용을 하여 전역 상태를 관리하는 저장소인 Store를 통해서 문제를 해결 할 수 있고, 컴포넌트3 에서 바로 컴포넌트6로 전달해줄 수 있기 때문에 데이터 흐름이 보다 더 깔끔해지는 것을 알 수가 있다.
Action 객체
가 생성된다.Action
객체는 Dispatch
함수의 인자로 전달된다.Dispathch
함수는 Action객체를 Reducer함수로 전달해줍니다.Reducer
함수는 Action
객체의 값을 확인하고, 그 값에 따라 전역 상태 저장소 Store
의 상태를 변경한다.Redux의 흐름
Action -> Dispatch -> Reducer -> Store 단방향의 흐름
Store는 상태가 관리되는 하나뿐인 저장소의 역할을 한다. Redux앱의 state가 저장되어 있는 공간이고
createStore
메서드를 통해서 Reducer를 연결해서 Store를 생성할 수 있다.
import {createStore} from 'redux'
const store = createStore(rootReducer)
Dispatch에서 전달받은 Action객체의 type
값에 따라 상태를 변경시키는 함수이다.
const count = 1
// 1
const counterReducer = (state = count, action) => {
// 2
switch (action.type) {
//action === 'INCREASE'일 경우
case 'INCREASE':
return state + 1
// action === 'DECREASE'일 경우
case 'DECREASE':
return state - 1
// action === 'SET_NUMBER'일 경우
case 'SET_NUMBER':
return action.payload
// 해당 되는 경우가 없을 땐 기존 상태를 그대로 리턴
default:
return state;
}
}
// 3
Reducer함수는
순수함수
여야 한다. 외부 요인으로 인해 기대한 값이 아닌 엉뚱한 값으로 상태가 변경되는 일이 없어야하기 때문
combineReducers
메서드를 사용해서 하나의 Reducer로 합쳐줄 수가 있다.
import { combineReducers } from 'redux';
const rootReducer = combineReducers({
counterReducer,
anyReducer,
...
});
어떤 액션을 취할 것인지 정의해 놓은 객체
이다.
// payload가 필요 없는 경우
{ type: 'INCREASE' }
// payload가 필요한 경우
{ type: 'SET_NUMBER', payload: 5 }
type
은 필수로 지정을 해주어야 한다. 해당 Action의 객체가 어떤 동작을 하는지 명시해주는 역할을 하기 때문에 대문자와 Snake Case로 작성을 해야하며 필요에 따라 payload를 작성해 구체적인 값을 전달한다.
// payload가 필요 없는 경우
const increase = () => {
return {
type: 'INCREASE'
}
}
// payload가 필요한 경우
const setNumber = (num) => {
return {
type: 'SET_NUMBER',
payload: num
}
}
Action을 보통 직접 작성하기 보단 Aciton 객체를 생성하는 함수를 만들어 사용하는 경우가 많고, 이런 함수를 액션생성자
라고 불린다.
payload는 action의 type에 따라 필요한 state값을 가지고있다.
Reducer로 Action을 전달해주는 함수이다. Dispatch의 전달인자로는 Action의 객체가 전달된다.
// Action 객체를 직접 작성하는 경우
dispatch( { type: 'INCREASE' } );
dispatch( { type: 'SET_NUMBER', payload: 5 } );
// 액션 생성자(Action Creator)를 사용하는 경우
dispatch( increase() );
dispatch( setNumber(5) );
Action 객체를 전달받은 Dispatch 함수는 Reducer를 호출하게 된다.
react-redux
라이브러리는 Redux를 활용할 수 있는 Hook들을 제공한다.
Action객체를 Reducer로 전달해 주는 Dispatch함수를 반환하는 메서드이다.
import { useDispatch } from 'react-redux'
const dispatch = useDispatch()
dispatch( increase() )
console.log(counter) // 2
dispatch( setNumber(5) )
console.log(counter) // 5
컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드이다.
// Redux Hooks 메서드는 'redux'가 아니라 'react-redux'에서 불러옵니다.
import { useSelector } from 'react-redux'
const counter = useSelector(state => state)
console.log(counter) // 1
Redux의 state 업데이트는 immutable한 방식
으로 변경해야 한다.
Redux의 장점인 변경된 state를 로그로 남기기 위해서는 꼭 필요한 작업이다.
reducer을 작성할 때에는 Object.assign
을 통해 새로운 객체를 만들어 리턴을 해야한다.
//initialState = 초기값을 의미
const itemReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_TO_CART:
return Object.assign({}, state, {
cartItems: [...state.cartItems, action.payload]
})
default:
return state;
}
}
+
-
버튼을 통해 count의 값을 바꾸어 주는 예제
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
// Provider는 store를 손쉽게 사용할 수가 있다.
import { Provider } from 'react-redux';
// redux에서 createStore를 불러와야 한다.
import { legacy_createStore as createStore } from 'redux';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
const count = 1;
// 액션 생성자
export const increase = () => {
return { type: 'INCREASE' };
};
// 액션 생성자
export const decrease = () => {
return { type: 'DECREASE' };
};
// Reducer를 생성할 때에는 초기 상태를 인자로 요구
const reducer = (state = count, action) => {
//Action 객체의 type 값에 따라 분기하는 switch 조건문입니다.
switch (action.type) {
//action === "INCREASE"일 경우
case 'INCREASE':
return state + 1;
//action === 'DECREASE'일 경우
case 'DECREASE':
return state - 1;
//action === 'SET_NUMBER' 일 경우
case 'SET_NUMBER':
return action.payload;
//해당 되는 경우가 없을 땐 기존 상태를 그대로 리턴
default:
return state;
}
};
// 변수를 통해 createStore를 만들어 주고 인자로 reducer를 반환 해준다.
const store = createStore(reducer);
root.render(
// Provider 안에 App을 넣어, App에서 store를 자유롭게 사용할 수가 있다.
<Provider store={store}>
<App />
</Provider>
);
App.js
import React from 'react';
import './style.css';
// react-redyx에서 useSelector, useDispatch를 불러온다.
import { useSelector } from 'react-redux';
import { useDispatch } from 'react-redux';
// Action Creater 함수 increase, decrease를 index.js에서 불러온다.
import { increase, decrease } from './index.js';
export default function App() {
// useDispatch의 실행값을 변수에 저장해서 dispatch함수를 사용한다.
const dispatch = useDispatch();
// useSeletor의 콜백 함수의 인자에 Store에 저장된 모든 state가 담긴다.
// Store에 저장된 모든 state를 return값을 통해 사용할 수가 있게 된다.
const state = useSelector((state) => state);
// dispatch를 통해 action객체를 Reducer 함수로 전달한다.
const plusNum = () => {
dispatch(increase());
};
const minusNum = () => {
dispatch(decrease());
};
return (
<div className="container">
{/* Store에서 꺼내온 state를 화면에 나타내기 위해 변수 state 사용*/}
<h1>{`Count: ${state}`}</h1>
<div>
<button className="plusBtn" onClick={plusNum}>
+
</button>
<button className="minusBtn" onClick={minusNum}>
-
</button>
</div>
</div>
);
}