Redux is a state management library that provides a single source of truth for application state and a predictable way to update it.
Under the hood, Redux works based on three core principles:
1️⃣ Single Source of Truth
- The entire app state is stored in a single object called the store.
- This makes state predictable and easy to debug.
const store = createStore(reducer);
2️⃣ State is Read-Only
- You cannot directly modify the state.
- The only way to update the state is by dispatching an action.
store.dispatch({ type: "INCREMENT" });
- Actions are plain objects describing what happened:
{ type: "INCREMENT", payload: 1 }
3️⃣ Changes via Pure Reducers
- Reducers are pure functions that take current state and action and return a new state.
function counterReducer(state = { count: 0 }, action) {
switch (action.type) {
case "INCREMENT":
return { ...state, count: state.count + 1 };
case "DECREMENT":
return { ...state, count: state.count - 1 };
default:
return state;
}
}
- Important: Reducers do not mutate the state; they return a new object.
4️⃣ Subscription & Re-rendering
- Components subscribe to the store to receive updates:
store.subscribe(() => console.log(store.getState()));
- When an action is dispatched:
- Store calls the reducer with the current state and action
- Reducer returns new state
- Store notifies subscribers → components re-render
5️⃣ Middleware (Optional)
- Middleware intercepts actions before they reach the reducer
- Useful for async logic, logging, or error handling
Example: redux-thunk allows async actions:
const fetchData = () => async (dispatch) => {
const res = await fetch("/api/data");
const data = await res.json();
dispatch({ type: "SET_DATA", payload: data });
};
6️⃣ Summary of Flow
Component dispatches action
↓
Action
↓
Reducer
↓
New State
↓
Store notifies subscribers
↓
Component re-renders with new state
⚡ In short:
Redux works by keeping a single state object, updating it via pure reducers based on dispatched actions, and notifying subscribed components to re-render. Middleware can intercept actions for async tasks or side effects, making state management predictable and scalable.