What is Action in Redux: Simple Explanation and Example
action is a plain JavaScript object that describes a change or event in the app. It must have a type property that tells Redux what happened, and it can include extra data to update the state.How It Works
Think of an action as a message sent to Redux saying "something happened." For example, when you click a button to add an item to a list, an action describes that event.
This message is a simple object with a type property that names the event, like "ADD_ITEM." It can also carry extra details, like the item to add.
Redux listens for these actions and uses them to decide how to update the app's state, similar to how a mailroom sorts letters based on their labels to deliver them correctly.
Example
This example shows an action object for adding a new todo item in a todo app.
const addTodoAction = { type: 'ADD_TODO', payload: { id: 1, text: 'Learn Redux actions' } }; console.log(addTodoAction);
When to Use
Use actions whenever you want to tell Redux that something happened and the state should change. This includes user interactions like clicks, form submissions, or receiving data from a server.
For example, when a user logs in, you dispatch a login action with their info. When data loads, you dispatch an action with that data. Actions keep your app's state changes clear and predictable.
Key Points
- An action is a plain object describing what happened.
- It must have a
typeproperty as a string. - It can carry extra data in other properties, often called
payload. - Actions are sent (dispatched) to Redux to update the state.