Redux의 여러 문제를 해결한 버전
이다
설치하기
npm install @reduxjs/toolkit react-redux
configureStore 안에 리듀서들을 넣어주면 된다.
import { configureStore } from '@reduxjs/toolkit'
export const store = configureStore({
reducer: {},
})
**index.js**
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { Provider } from "react-redux";
import store from "./store";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<Provider store={store}>
<React.StrictMode>
<App />
</React.StrictMode>
</Provider>
);
Redux Toolkit의
createSlice
state의 초기값, Reducer와 action을 넣어주자
import { configureStore, createSlice } from "@reduxjs/toolkit";
const counterSlice = createSlice({
name:'counter',
initialState : { counter : 0},
reducers: {
increment(state,action) {
state.counter++;
},
decrement(state,action) {
state.counter--;
},
addBy(state,action) {
state.counter += action.payload;
}
}
})
export const actions = counterSlice.actions;
const store = configureStore({
reducer: counterSlice.reducer
});
export default store;
**App.js**
import { useSelector, useDispatch } from 'react-redux';
import './App.css';
import {actions} from './store/index'
function App() {
const counter = useSelector((state) => state.counter)
const dispatch = useDispatch();
const increment = () => {
dispatch(actions.increment())
}
const decrement = () => {
dispatch(actions.decrement())
}
const addBy = () => {
dispatch(actions.addBy(10))
}
return (
<div className="App">
<h1>Count</h1>
<h2>{counter}</h2>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
<button onClick={addBy}>Add by 10</button>
</div>
);
}
export default App;
리덕스를 이용한 것 보다 간단하고 편해서 사용하기 좋았지만 익숙하지 않기에 더 많은 예제를 통해서 리덕스 툴킷에 익숙해져서 잘 사용하고 싶다.