01
시작하기
리듀서
리듀서는 (state, action) => state 형태의 순수 함수입니다.
redux
function counter(state = 0, action) {
switch (action.type) {
case "INCREMENT": return state + 1;
case "DECREMENT": return state - 1;
default: return state;
}
}스토어
스토어가 상태를 보관하며, dispatch로 상태를 변경합니다.
redux
import { createStore } from "redux";
const store = createStore(counter);
store.dispatch({ type: "INCREMENT" });
console.log(store.getState());Redux Toolkit
Redux Toolkit의 createSlice로 Redux를 간소화할 수 있습니다.
redux
import { createSlice, configureStore } from "@reduxjs/toolkit";
const counter = createSlice({
name: "counter",
initialState: 0,
reducers: {
increment: s => s + 1,
decrement: s => s - 1,
}
});
const store = configureStore({ reducer: counter.reducer });02
React 통합
useSelector
상태를 읽고 액션을 디스패치하기 위한 훅입니다.
redux
import { useSelector, useDispatch } from "react-redux";
function Counter() {
const count = useSelector(s => s);
const dispatch = useDispatch();
return <button onClick={() => dispatch({type: "INCREMENT"})}>{count}</button>;
}Was this helpful?