redux를 통해 state를 유연하게 관리 할 필요가 있다.
상위 컴포넌트에서 하위 컴포넌트를 계속해서 호출 할 경우, props 지옥에서 벗어나기 위해서도 필요하기 때문임.
설정 :
$ npm install @reduxjs/toolkit react-redux
혹은
$ npx create-react-app my-app --template redux
template으로 지정해서 생성.
cra로 react 프로젝트를 만든다면, 필요없는 라이브러리가 많이 설치되어, 추천하지 않는 경우도 있다.
CRA 커맨드가 아닌 수동으로 만든 프로젝트라면,
# NPM
npm install redux
# Yarn
yarn add redux
커맨드를 사용해도 된다.
toolkit 을 쓰는 이유는 공식 문서 상에서 추천 할 뿐만 아니라, 기존의 redux에서 불편한 기능을 제외하고,
유용한 기능을 추가했기 때문.
https://redux.js.org/introduction/getting-started
Getting Started with Redux | Redux
Introduction > Getting Started: Resources to get started learning and using Redux
redux.js.org
공식 문서와 tutorial은 동일함.
Project 구조 ::
index.js
🥝 provider 하위에 있다면, 다 store에 설정한 state 값들을 참조 할 수 있다.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import store from './app/store';
import {Provider} from "react-redux";
import {Counter} from "./app/features/counter/Counter";
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<Provider store={store}>
{/*<App />*/}
<Counter />
</Provider>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './features/counter/counterSlice';
export default configureStore({
reducer: {
counter: counterReducer
}
})
Counter.js
단순 버튼 클릭시 state의 값을 변경 ( +1 / -1 ) 처리한다.
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import { decrement, increment } from "./counterSlice";
export function Counter() {
const count = useSelector(state => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<div>
<button
aria-label="Increment value"
onClick={() => dispatch(increment())}
>
Increment
</button>
<span>{count}</span>
<button
aria-label="Decrement value"
onClick={() => dispatch(decrement())}>
Decrement
</button>
</div>
</div>
)
}
counterSlice.js
🍗 toolkit에서는 기존에서 쓰던 switch / case로 작성하던 reducers 셋팅 구조가 바뀌었다.
import { createSlice } from "@reduxjs/toolkit";
export const counterSlice = createSlice({
name: 'counter',
initialState: {
value:0
},
reducers: {
increment: state => {
state.value += 1
},
decrement: state => {
state.value -= 1
},
incrementByAmount: (state, action) => {
state.value += action.payload
}
}
})
export const {increment, decrement, incrementByAmount} = counterSlice.actions;
export default counterSlice.reducer;