Redux
What Is Redux?
A state management library that centralizes all state in a single store. It is ideal for large applications.
Three Principles
- Single Source of Truth — All state lives in one object tree
- State is Read-Only — It can only be changed by dispatching actions
- Pure Reducers — Functions that receive state + action and return a new state
Setup with Redux Toolkit
npm install @reduxjs/toolkit react-redux
// store.js
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './counterSlice';
export const store = configureStore({
reducer: { counter: counterReducer },
});
// App.js
import { Provider } from 'react-redux';
<Provider store={store}><MainApp /></Provider>
Selectors & Dispatch
import { useSelector, useDispatch } from 'react-redux';
import { increment } from './counterSlice';
function Counter() {
const count = useSelector(state => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<span>{count}</span>
<button onClick={() => dispatch(increment())}>Add</button>
</div>
);
}
Slices (createSlice)
import { createSlice, nanoid } from '@reduxjs/toolkit';
const todosSlice = createSlice({
name: 'todos',
initialState: [],
reducers: {
addTodo: {
reducer: (s, a) => { s.push(a.payload); },
prepare: (text) => ({ payload: { id: nanoid(), text, completed: false } }),
},
toggleTodo: (s, a) => {
const t = s.find(t => t.id === a.payload);
if (t) t.completed = !t.completed;
},
},
});
export const { addTodo, toggleTodo } = todosSlice.actions;
export default todosSlice.reducer;
RTK uses Immer behind the scenes — the code looks mutable, but is actually immutable. Final chapter: the complete React Cheatsheet!