Action types
- React course
- Intermediate
- Lesson 14/80
- 4 min
Learn to define action types as constants.
Action types
Action types are usually defined as string constants: const ADD = "ADD"; const REMOVE = "REMOVE";. This prevents typos and eases refactoring.
When the same string is used across many files, a single-character typo can go unnoticed for a long time. With constants, the IDE gives autocomplete and error checking. So in team work it's almost mandatory.
For type safety with TypeScript, you define a union type like type Action = { '{ type: typeof ADD; payload: Item }' } | .... This catches errors at compile time.
Payload usage
Payload carries the action's extra data. Like { '{ type: "ADD", payload: { id: 1, name: "Bread" } }' }. The reducer takes the payload and adds it to state.
An action can have no payload: { '{ type: "CLEAR" }' }. This is enough for cases like resetting state. Not every action must carry a payload.
Good habit: keep the payload type consistent. If an action sometimes carries an object, sometimes a number, the code gets harder to read. A single payload type is cleaner.
Practice Action constants and reducer
Complete the skeleton. Define ADD and REMOVE as string constants. Write a listReducer function: with switch(action.type), in the ADD case return { '{ ...state, items: [...state.items, action.payload] }' }; in the REMOVE case return { '{ ...state, items: state.items.filter(i => i.id !== action.payload.id) }' }; default returns state. Export the reducer.
Starter code
// Write the constants and listReducer hereSample solution
const ADD = "ADD";
const REMOVE = "REMOVE";
function listReducer(state, action) {
switch (action.type) {
case ADD:
return { ...state, items: [...state.items, action.payload] };
case REMOVE:
return { ...state, items: state.items.filter((i) => i.id !== action.payload.id) };
default:
return state;
}
}
export default listReducer;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why are action types constants?
- To run faster
- To skip useEffect
- To prevent typos Correct answer
- To change CSS
Explanation: Constants prevent typos.
2 Action field
The field carrying the action's type is ____.
The field carrying the action's type is type.
Explanation: type carries the action's type.
3 Match the action fields
| Term | Meaning |
|---|---|
type |
Type |
payload |
Extra data |
ADD |
Add |
CLEAR |
Reset |