리덕스는 가장 많이 사용하는 리액트 상태 관리 라이브러리이다.
상태에 어떠한 변화가 필요하면 액션이란 것을 발생한다. 이는 하나의 객체로 표현되는데 액션 객체는 다음과 같은 형식으로 되어있다.
{
type : ‘TOGGLE_VALUE’
}
액션 객체는 위와 같이 type 필드를 반드시 가지고 있어야 한다. 이 값을 액션의 이름이라고 생각하면 된다.
그 외의 값들은 나중에 상태 업데이트를 할 때 참고해야 할 값이며, 작성자 마음대로 넣을 수 있다.
예시 액션
{
type : 'ADD_TODO',
data : {
id : 1,
text : '리덕스 배우기'
}
}
{
type : 'CHANGE_INPUT',
text : '안녕하세요'
}
액션 생성 함수는 액션 객체를 만들어 주는 함수이다.
예시 액션함수
const changeInput = (text) => {
type : 'CHANGE_INPUT',
text
}
어떤 변화를 일으켜야 할 때마다 액션 객체를 만들어야 하는데 매번 직접 액션 객체를 만들기에는 번거로우며 만드는 과정에서 실수를 할 수 있기 때문에 이러한 일을 방지하기 위해 이를 함수로 만들어 관리한다.
리듀서는 변화를 일으키는 함수이다. 액션을 만들어서 발생시키면 리듀서가 현재 상태와 전달받은 액션 객체를 파라미터로 받아 온다. 그리고 두 값을 참고하여 새로운 상태를 만들어서 반환해준다.
Provider
state를 어떤 컴포넌트들에게 제공할 것인지에 대한 가장 바깥쪽에 정의(울타리)
state 변화를 주고 싶은 컴포넌트에 Provider를 씌우는데 적용법은
변화주고싶은 컴포넌트(상위 컴포넌트에 넣어도 됨)
useSelector
Provider로 감싸줘야 사용가능
store에 저장된 state를 가져올 수 있는 역할이다.
상위
function reducer(state, action) {
if (state === undefined) {
return {
number: 1,
};
}
const newState = { ...state };
return newState;
}
말단
const number = useSelector((state) => state.number);
나중에 createStore 함수를 사용하여 스토어를 만들 때는 리듀서를 하나만 사용해야 한다. 그렇기 때문에 하나의 프로젝트에서 여러 개의 리듀서를 만들었을 경우 하나로 합쳐줘야 하는데 이 작업은 리덕스에서 제공하는 conbimeReducer라는 유틸 함수를 사용하면 된다.
import { combineReducers } from "redux";
import counter from "./counter";
import todos from "./todos";
const rootReducer = combineReducers({
counter,
todos,
});
export default rootReducer;
파일 이름을 index.js로 만들면 나중에 불러올 때 디렉터리 이름까지만 입력하여 불러올 수 있다.
import rootReducer from ‘./modules’;
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createStore } from "redux";
import rootReducer from "./modules";
import { Provider } from "react-redux";
const store = createStore(rootReducer);
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
<React.StrictMode>
,
document.getElementById("root")
);
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { createStore } from "redux";
import rootReducer from "./modules";
import { Provider } from "react-redux";
import { composeWithDevTools } from "redux-devtools-extension";
const store = createStore(rootReducer, composeWithDevTools());
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById("root")
);
액션 타입, 액션 생성 함수, 리듀서를 각각 다른 파일에 저장할지, Ducks 패턴으로 할 것인지 정하기
액션 타입 정의하기
const INCREASE = "counter/INCREASE";
const DECREASE = "counter/DECREASE";
액션 타입은 대문자로 정의하고, 문자열 내용은 모듈이름/액션이름으로 작성한다.
3.액션 생성 함수 만들기
const INCREASE = "counter/INCREASE";
const DECREASE = "counter/DECREASE";`````
export const increase = () => ({ type: "INCREASE" });
export const decrease = () => ({ type: "DECREASE" });