01
Getting Started
Reducer
Reducers are pure functions (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;
}
}Store
Store holds state; dispatch to change it.
redux
import { createStore } from "redux";
const store = createStore(counter);
store.dispatch({ type: "INCREMENT" });
console.log(store.getState());Redux Toolkit
Redux Toolkit simplifies Redux with createSlice.
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 Integration
useSelector
Hooks for reading state and dispatching actions.
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?