Redux는 상태의 중앙 관리를 위한 상태 관리 도구이다.
전역 상태를 생성하고 관리하기 위한 라이브러리 이다.
리덕스는 전역 상태를 보관하는 저장소, 상태 저장소에 접근을 위한 리듀서, 리듀서에 행동을 지시하는 액션, 저장소에 보관된 상태를 가지고 오는 서브스크립션으로 구분된다.
우선 redux와 react-redux가 설치되어 있어야 한다.
npm install redux react-redux
Redux Store 만들기
예제) 버튼을 누르면 카운터 증감하고, 토글 버튼으로 보여주고 사라지게 하는 예제이다.
보통은 src 밑에 store 라는 폴더를 만들고 index.js라고 파일을 만들어 준다.
index.js
import {createStore} from 'redux';
const initalState = { counter: 0, showCounter: true};
const counterReducer = (state = initalState, action) => {
if (action.type === 'increment') {
return {
counter: state.counter + 1,
showCounter: state.showCounter
}
}
if (action.type === 'decrement') {
return {
counter: state.counter - 1,
showCounter: state.showCounter
}
}
if (action.type === 'increaseby5') {
return {
counter: state.counter + action.amount;
showCounter: state.showCounter
}
}
if (action.type === 'toggle') {
return {
counter: state.counter,
showCounter: !state.showCounter
}
}
return state;
};
const store = createStore(counterReducer);
reducer를 정의할 때 분기처리를 action.type으로 처리해준다.
주의할점은 return을 해줄 때 처음에 정의했던 값들을 전부 넘겨줘야 한다. 그렇지 않으면 값을 불러오지 못한다.
예를들어 action.type이 'toggle' 인 경우에 counter: state.counter 만 넘겨주고 showCounter을 넘겨주지 않는다면 데이터는 손실된다.
그리고 state의 고유 값을 변경해서는 안되고 값에 접근하여 데이터를 수정해야한다. 그렇지 않으면 데이터가 꼬일 수 있다.
App.js 와 같은 레벨에 있는 index.js
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import "./index.css";
import App from "./App";
import store from "./store/index";
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
제공자 Component인 Provider 을 import 해주고 App을 감싸준다.
위에서 만들었던 store을 import 해주고 제공자 Component에서 store prop으로 내려준다.
Counter.js
import {useSelector, useDispatch} from 'react-redux';
const Counter = () => {
const dispatch = useDispatch();
const counter = useSelector(state => state.counter);
const show = useSelector(state => state.showCounter);
const incrementHandler = () => {
dispatch({type: 'increment'});
};
const increaseHandler = () => {
dispatch({type: 'increase', amount: 5});
};
const decrementHandler = () => {
dispatch({type: 'decrement'});
};
const toggleCounterHandler = () => {
dispatch({type: 'toggle'});
};
return (
<main>
<h1>Counter</h1>
{show && <div>{counter}</div>}
<div>
<button onClick={incrementHandler}>Increment</button>
<button onClick={increaseHandler}>Increment by 5</button>
<button onClick={decrementHandler}>Decrement</button>
</div>
<button onClick={toggleCounterHandler}>Toggle Counter</button>
);
};
useSelector로 reducer에 있는 데이터에 접근하여 값을 가지고오고
useDispatch로 reducer에 있는 데이터에 접근하여 값을 변경해준다.
'React > Redux' 카테고리의 다른 글
| Redux Toolkit (0) | 2022.07.28 |
|---|
댓글