- React Redux Toolkit #1 Tutorial for Beginners
https://youtu.be/u3KlatzB7GM?list=PL0Zuz27SZ-6M1J5I1w2-uZx36Qp6qhjKo
전역 상태 관리자
가장 기본적인 실습예제로 전체 구조를 파악하기좋습니다.
표시되는 count state를 1씩 증감, 그리고 사용자가 입력한 값만큼 증가시키거나 리셋 시키는 기능을 하는 Counter를 만들어보겠습니다.
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from '../features/counter/counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
}
})
전체 상태를 변경할 수 없는 객체 트리에 저장
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { store } from './app/store';
import { Provider } from 'react-redux';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
이렇게 Provider로 App을 감싸면 전체 상태를 앱에서 사용할 수 있게 됩니다.
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
count: 0
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
// anonymous function
increment: (state) => {
state.count += 1;
},
decrement: (state) => {
state.count -= 1;
},
reset: (state) => {
state.count = 0;
},
incrementByAmount: (state, action) => {
state.count += action.payload;
}
}
});
export const { increment, decrement, reset, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
redux 상태 개체를 여러 상태 슬라이스로 분하라여 가져옴
import { useSelector, useDispatch } from "react-redux";
import {
increment,
decrement,
reset,
incrementByAmount
} from './counterSlice';
import { useState } from "react";
const Counter = () => {
const count = useSelector((state) => state.counter.count);
const dispatch = useDispatch();
const [incrementAmount, setIncrementAmount] = useState(0);
const addValue = Number(incrementAmount) || 0;
const resetAll = () => {
setIncrementAmount(0);
dispatch(reset());
}
return (
<section>
<p>{count}</p>
<div>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
<input
type="text"
value={incrementAmount}
onChange={(e) => setIncrementAmount(e.target.value)}
/>
<div>
<button onClick={() => dispatch(incrementByAmount(addValue))}>Add Amount</button>
<button onClick={resetAll}>Reset</button>
</div>
</section>
)
}
export default Counter
- useSelector 블로그
https://phsun102.tistory.com/85- Hooks/useSelector()
https://react-redux.js.org/api/hooks
Allows you to extract data from the Redux store state, using a selector function.