React
Action types
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.
Exercise 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.
Show example 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;
Test yourself
-
Why are action types constants?
- To run faster
- To skip useEffect
- To prevent typos
- To change CSS
Show answer
To prevent typos — Constants prevent typos.
-
Action field
The field carrying the action's type is ____.
Show answer
The field carrying the action's type is type.
-
Match the action fields
- type
- Type
- payload
- Extra data
- ADD
- Add
- CLEAR
- Reset
Next lesson: Composition