Redux
Redux is a predictable state container based on three core principles.
Three principles
- Single source of truth - one global store.
- State is read-only - only actions can trigger changes.
- Changes via pure functions - reducers are pure.
Data flow
text
UI -> dispatch(action) -> reducer(state, action) -> new state -> UICore pieces
ts
// 1 - action
const increment = { type: 'counter/increment', payload: 1 };
// 2 - reducer
function counterReducer(state = 0, action) {
switch (action.type) {
case 'counter/increment': return state + action.payload;
default: return state;
}
}
// 3 - store (createStore is deprecated - shown only to explain the idea)
const store = createStore(counterReducer);
store.dispatch(increment);
store.getState(); // 1Redux Toolkit (modern Redux)
ts
import { createSlice, configureStore } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => { state.value += 1; }, // immer - looks mutable
decrement: (state) => { state.value -= 1; },
incrementBy: (state, action) => { state.value += action.payload; },
},
});
export const { increment, decrement, incrementBy } = counterSlice.actions;
const store = configureStore({ reducer: { counter: counterSlice.reducer } });In components
tsx
// typed hooks: useAppSelector = useSelector.withTypes<RootState>()
const value = useAppSelector(s => s.counter.value);
const dispatch = useAppDispatch();
<button onClick={() => dispatch(increment())}>+</button>Redux solves predictability and debuggability - the Redux DevTools let you time-travel through every state change. For most modern apps Zustand or Jotai is simpler, but Redux still dominates in large enterprise codebases.
updated
did you know it?