Blog>
Snippets

Creating an Action in Redux

Show how to define a Redux action with a type and an optional payload, which will be dispatched to change state.
// Action Types
const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';

// Action Creators
// Increment Action Creator - no payload
function increment() {
  return {
    type: INCREMENT
  };
}

// Decrement Action Creator with payload
function decrement(amount) {
  return {
    type: DECREMENT,
    payload: amount
  };
}

// Dispatching Actions
// would be done in the UI logic, e.g., a button click handler
// dispatch(increment());
// dispatch(decrement(5));
This code defines two action types, INCREMENT and DECREMENT, as well as their corresponding action creators. The increment action creator generates an action without any additional information other than its type. The decrement action creator, on the other hand, specifies a payload that holds the amount by which the value should be decremented. Dispatching these actions would typically be done in response to user interactions in the UI.