상태 관리 라이브러리가 없어도 가능하나, 규모가 커지면 사용하는게 더 좋다.
전역에서 상태를 관리할 수 있어(store) Props Drilling 이슈 해결
Single source of truth(신뢰할 수 있는 단일 출처) 원칙을 유지하게 도와준다.
Props Drilling: props를 컴포넌트들이 오로지 props를 전달하는 용도로만 쓰이면서 props가 필요한 하위 컴포넌트로 계속 전달되는 과정이 발생할 수 있다. 이로 인해 불필요한 컴포넌트들의 렌더링이 일어나고, 데이터의 출처를 쉽게 파악할 수 없어서 코드의 가독성이 낮아지는 현상이 나타난다.
React Context, Redux, MobX 외 에도 recoil, zustand 등이 있다.
그 중 Redux를 가장 많이 사용한다.
Action → Dispatch → Reducer → Store(New State)
- 상태가 변경되어야 하는 이벤트가 발생하면(UI에서 상호작용을 하면), 변경될 상태에 대한 정보가 담긴 Action 객체가 생성됩니다.
- 이 Action 객체는 Dispatch 함수의 인자로 전달 됩니다.
- Dispatch 함수는 Action 객체를 Reducer 함수로 전달해줍니다.
- Reducer 함수는 Action 객체의 값을 확인하고, 그 값에 따라 전역 상태 저장소 Store의 상태를 변경합니다.
- 상태가 변경되면, React는 화면을 다시 렌더링 합니다.
1. Single source of truth
동일한 데이터는 항상 같은 곳에서 가지고 와야 한다는 의미로, Redux에는 데이터를 저장하는 Store라는 단 하나뿐인 공간이 있음과 연결이 되는 원칙
2. State is read-only
상태는 읽기 전용이라는 뜻으로, React에서 상태갱신함수로만 상태를 변경할 수 있었던 것처럼, Redux의 상태도 직접 변경할 수 없음을 의미한다. 즉, Action 객체가 있어야만 상태를 변경할 수 있음과 연결되는 원칙
3. Changes are made with pure functions
변경은 순수함수로만 가능하다는 뜻으로, 상태가 엉뚱한 값으로 변경되는 일이 없도록 순수함수로 작성되어야하는 Reducer와 연결되는 원칙
useDispatch()
는 Action 객체를 Reducer로 전달해 주는 Dispatch 함수를 반환하는 메서드이다.
useSelector()
는 컴포넌트와 state를 연결하여 Redux의 state에 접근할 수 있게 해주는 메서드이다.
상태를 사용하기 위해 가져와주는 훅
해당되는 경우가 없을 때의 상태를 새로 생성하여 리턴 X, 기존 상태를 그대로 리턴한다.
const counterReducer = (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;
}
};
// index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { legacy_createStore as createStore } from 'redux';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
// 액션 생성자 함수를 type 별로 만들어준다.
export const increase = () => {
return {
type: 'INCREASE',
};
};
export const decrease = () => {
return {
type: 'DECREASE',
};
};
export const setNumber = (num) => {
return {
type: 'SET_NUMBER',
payload: num
}
}
// state 초기값
const count = 1;
// Reducer가 리턴하는 값이 새로운 상태가 된다
const counterReducer = (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;
}
};
// store 객체를 생성해주고, 위에서 만든 리듀서를 전달
const store = createStore(counterReducer);
root.render(
// App 컴포넌트를 Provider로 감싸준 후 props로 변수 store를 전달
<Provider store={store}>
<App />
</Provider>
);
// App.js
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increase, decrease } from './index.js';
// UI에 상호작용 시 action 객체 생성 및 dispatch로 action 전달
export default function App() {
const dispatch = useDispatch();
// useSelector 훅을 사용하여 state에 접근
const state = useSelector((state) => state);
const plusNum = () => {
dispatch(increase());
};
const minusNum = () => {
dispatch(decrease());
};
return (
<div className="container">
{/* Store에서 꺼내온 state를 화면에 나타내기 위해 변수 state를 넣어준다. */}
<h1>{`Count: ${state}`}</h1>
<div>
{/* 플러스 버튼 누르면 plusNum 실행 */}
<button className="plusBtn" onClick={plusNum}>
+
</button>
{/* 마이너스 버튼 누르면 minusNum 실행 */}
<button className="minusBtn" onClick={minusNum}>
-
</button>
</div>
</div>
);
}
Action
// Action/index.js
// 변수 선언으로 재사용성 높이기
export const INCREASE = 'INCREASE';
export const DECREASE = 'DECREASE';
// 액션 생성자 함수를 type 별로 만들어준다.
export const increase = () => {
return {
type: INCREASE,
};
};
export const decrease = () => {
return {
type: DECREASE,
};
};
Dispatch
// Stroe/App.js
import React from 'react';
import './style.css';
import { useSelector, useDispatch } from 'react-redux';
import { increase, decrease } from './Actions';
// UI에 상호작용 시 action 객체 생성 및 dispatch로 action 전달
export default function App() {
const dispatch = useDispatch();
const state = useSelector((state) => state);
const plusNum = () => {
dispatch(increase());
};
const minusNum = () => {
dispatch(decrease());
};
return (
<div className="container">
<h1>{`Count: ${state}`}</h1>
<div>
<button className="plusBtn" onClick={plusNum}>
+
</button>
<button className="minusBtn" onClick={minusNum}>
-
</button>
</div>
</div>
);
}
Reducers
// Reducers/index.js
import { initialState } from './initialState.js';
import { INCREASE, DECREASE, increase, decrease } from '../Actions';
// Reducer가 리턴하는 값이 새로운 상태가 된다
export const counterReducer = (state = initialState, action) => {
switch (action.type) {
case INCREASE:
return state + 1;
case DECREASE:
return state - 1;
default:
return state;
}
};
// Reducers/initialState.js
// state 초기값
export const initialState = 1;
Store
// Store/index.js
import React from 'react';
import { createRoot } from 'react-dom/client';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './Store';
const rootElement = document.getElementById('root');
const root = createRoot(rootElement);
root.render(
// App 컴포넌트를 Provider로 감싸준 후 props로 변수 store를 전달
<Provider store={store}>
<App />
</Provider>
);