Redux is a predictable state container using a single store with pure reducer functions; Redux Thunk is middleware that enables async logic by allowing action creators to return functions that can dispatch actions and access state.
Redux Core Concepts:
{ type: 'ADD_TODO', payload }(state, action) => newStateUnidirectional Data Flow:
UI → dispatch(action) → reducer → new state → UI re-renders
What is a Thunk?
dispatch and getStateWhy Redux Thunk?
Modern Redux Toolkit:
configureStore - Sets up store with good defaultscreateSlice - Generates actions + reducers togethercreateAsyncThunk - Handles async with pending/fulfilled/rejected// Action types
const ADD_TODO = 'todos/add';
const TOGGLE_TODO = 'todos/toggle';
// Action creators
const addTodo = (text) => ({
type: ADD_TODO,
payload: { id: Date.now(), text, completed: false }
});
const toggleTodo = (id) => ({
type: TOGGLE_TODO,
payload: id
});
// Reducer (pure function!)
const initialState = { todos: [], loading: false, error: null };
function todosReducer(state = initialState, action) {
switch (action.type) {
case ADD_TODO:
return {
...state,
todos: [...state.todos, action.payload]
};
case TOGGLE_TODO:
return {
...state,
todos: state.todos.map(todo =>
todo.id === action.payload
? { ...todo, completed: !todo.completed }
: todo
)
};
default:
return state;
}
}
// Store setup
import { createStore } from 'redux';
const store = createStore(todosReducer);
// Usage
store.dispatch(addTodo('Learn Redux'));
store.dispatch(toggleTodo(1));
console.log(store.getState());