What is an action in Redux?
In Redux, an action is a plain object that describes what happened in the application.
An action does not change state itself - it just tells the reducer which event occurred.
Formally
An action is an object with a required type field that describes the type of event:
javascript
{ type: 'ADD_TODO' }You can also pass additional data (payload) to communicate the details of the action:
javascript
{
type: 'ADD_TODO',
payload: { text: 'Buy bread' }
}Example
Suppose we have a reducer for a list of todos:
javascript
function todosReducer(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return [...state, action.payload]
case 'REMOVE_TODO':
return state.filter(todo => todo.id !== action.payload.id)
default:
return state
}
}Now you can call:
javascript
store.dispatch({
type: 'ADD_TODO',
payload: { id: 1, text: 'Buy bread' }
})The reducer receives this action and returns the new state.
Rules for actions
- An action is just data, with no logic.
- It must have a
typefield - a string that uniquely identifies the action. - An action must be serializable (that is, consist of plain JS values, with no functions, classes, Promises, and so on).
- The reducer decides what to do with this action.
Action creator
Actions are often created through dedicated functions:
javascript
function addTodo(text) {
return {
type: 'ADD_TODO',
payload: { text }
}
}
// Usage:
dispatch(addTodo('Buy milk'))This is convenient because:
- Action creators can be reused
- You can add validation or extra computation
Summary
| Term | What it is | Example |
|---|---|---|
| Action | Description of an event | { type: 'LOGIN_SUCCESS', payload: user } |
| Reducer | A function that updates state based on an action | (state, action) => newState |
| Dispatch | The mechanism that sends an action to the store | dispatch({ type: 'LOGOUT' }) |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.