Redux Actions and Reducers
At the heart of Redux are **actions** and **reducers**. Actions describe what happened, and reducers specify how the state changes in response. Together they form a predictable pattern for updating your application's state.
Actions
Actions are plain JavaScript objects that have a `type` field (usually a string constant) and an optional `payload` containing data. They represent the intention to change state.
<!-- Action type constants (optional but recommended) -->const ADD_TODO = 'ADD_TODO';const TOGGLE_TODO = 'TOGGLE_TODO';
<!-- Action creators functions that return action objects -->function addTodo(text) { return { type: ADD_TODO, payload: { text, completed: false } };}
function toggleTodo(id) { return { type: TOGGLE_TODO, payload: { id } };}Reducers
Reducers are pure functions that take the current state and an action, and return the new state. They specify how the state changes in response to actions.
<!-- Initial state -->const initialState = { todos: [] };
<!-- Reducer -->function todoReducer(state = initialState, action) { switch (action.type) { case ADD_TODO: return { ...state, todos: [...state.todos, { id: Date.now(), ...action.payload }] }; case TOGGLE_TODO: return { ...state, todos: state.todos.map(todo => todo.id === action.payload.id ? { ...todo, completed: !todo.completed } : todo ) }; default: return state; }}Combining Reducers
As your app grows, you can split reducers into multiple files and combine them using `combineReducers`.
import { combineReducers } from 'redux';import todosReducer from './todosReducer';import userReducer from './userReducer';
const rootReducer = combineReducers({ todos: todosReducer, user: userReducer});Two Minute Drill
- Actions are plain objects with a `type` and optional `payload` they describe an event.
- Action creators are functions that return action objects for reuse.
- Reducers are pure functions that take current state and an action, and return the new state.
- Reducers must never mutate state always return a new object.
- Combine multiple reducers with `combineReducers` for modularity.
Need more clarification?
Drop us an email at career@quipoinfotech.com
