Redux toolkit 등장 배경
App.js
import React from 'react';
function Counter() {
return(
<div>
<button>+</button> 0
</div>
)
}
export default function App() {
return (
<div>
<Counter></Counter>
</div>
);
}
import { createStore } from 'redux';
function reducer(state, action) {
return state;
}
const initialState = {value:0}
import {Provider, useSelecor} from 'react-redux';
const store = createStore(reducer, initialState);
<Provider store={store}>
</Provider>
import { useSelector } from 'react-redux';
const count = useSelector(state=>state.value);
<button>+</button> {count}
import { useDispatch } from 'react-redux';
const dispatch = useDispatch();
<button onClick={()=>{
dispatch({type:'up', step:2});
}}>+</button>{count}
function reducer(state, action) {
if(action.type === 'up'){
return {...state, value:state.value + action.step}
}
return state;
}
최종코드
import React from 'react';
import { createStore, useSelector, useDispatch } from 'redux';
function reducer(state, action) {
if(action.type === 'up'){
return {...state, value:state.value + action.step}
}
return state;
}
const initialState = {value:0}
const store = createStore(reducer, initialState);
function Counter() {
const dispatch = useDispatch();
const count = useSelector(state=>state.value);
return(
<div>
<button onClick={() => {
dispatch({type:'up', step:2});
}}>+</button>{count}
</div>
)
}
export default function App() {
return (
<Provider store={store}>
<div>
<Counter></Counter>
</div>
</Provider>
);
}
npx create-react-app my-app --template redux
npm install @reduxjs/toolkit

import {createSlice} from '@reduxs/tooltit';
const CounterSlice = createSlice({
name:'counter',
initialState:{valu:0},
reducers:{
up:{state, action} => {
state.value = state.value + action.step;
}
}
});
import { configureStore } from '@reduxjs/toolkit';
// 하나의 거대한 store
const store = configureStore({
reducer:{
counter:counterSlice.reducer
}
});
dispatch(counterSlice.actions.up(2));
const CounterSlice = createSlice({
name:'counter',
initialState:{valu:0},
reducers:{
up:{state, action} => {
state.value = state.value + action.payload;
}
}
});