Redux - Introduction
Who is this for? Beginners who know basic React. You’ll learn what Redux is, why teams use it, and see a tiny, runnable example.
What is Redux?
Redux is a predictable state container. It centralizes app state in a single store, updates it with pure reducers, and changes happen via actions.
Key benefits
- Predictability: State changes are pure and traceable.
- Debuggable: Time travel and action logs (in devtools).
- Single source of truth: One store holds the state tree.
Try it: Minimal Redux store
View source
const { createStore } = Redux;
function counter(state = { value: 0 }, action){
switch(action.type){
case 'inc': return { value: state.value + 1 };
case 'dec': return { value: state.value - 1 };
default: return state;
}
}
const store = createStore(counter);
const out = document.getElementById('redux-out');
store.subscribe(() => { out.textContent = JSON.stringify(store.getState()); });
// Initial render
out.textContent = JSON.stringify(store.getState());
// UI wiring
document.getElementById('btn-inc').onclick = () => store.dispatch({ type: 'inc' });
document.getElementById('btn-dec').onclick = () => store.dispatch({ type: 'dec' });
Syntax primer
createStore(reducer)
creates a Redux store (in modern apps, useconfigureStore
from Redux Toolkit).reducer(state, action)
returns new state based on the action.store.dispatch({type:'inc'})
sends an action;store.getState()
reads state;store.subscribe
listens for updates.
Common pitfalls
- Mutating state in reducers—always return new objects.
- Too many stores—in almost all apps, use a single store.