Blog>
Snippets

Refactoring with Action Type Constants

Demonstrate how to refactor a Redux application to use constant action type definitions, thus enabling easy updates and preventing bugs when types change.
// actionTypes.js
// Define action type constants
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
This file defines the action type constants to avoid typos and reuse them throughout the Redux application.
// actions.js
import { INCREMENT, DECREMENT } from './actionTypes';

// Action creators using the constants
export function increment() {
  return { type: INCREMENT };
}

export function decrement() {
  return { type: DECREMENT };
}
Action creators use the imported constants rather than string literals to specify the type of action being dispatched.
// reducer.js
import { INCREMENT, DECREMENT } from './actionTypes';

// Reducer function using the constants
function counter(state = 0, action) {
  switch (action.type) {
    case INCREMENT:
      return state + 1;
    case DECREMENT:
      return state - 1;
    default:
      return state;
  }
}

export default counter;
The reducer uses the imported constants to handle specific actions. This ensures that the action types checked in the reducer match those dispatched by the action creators.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Redux Refactoring Example</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
    <script type="module" src="./index.js"></script>
</head>
<body>
    <div id="app">
        <!-- Your HTML content goes here -->
    </div>
</body>
</html>
The HTML file includes the Redux library and the main JavaScript module file for the application, where the Redux store and logic will be initialized.
// index.js
import { createStore } from 'redux';
import counter from './reducer.js';
import { increment, decrement } from './actions.js';

// Create Redux store
const store = createStore(counter);

// Dispatching actions using the action creators
store.dispatch(increment());
store.dispatch(decrement());
The entry JavaScript file where the Redux store is created and actions are dispatched using the action creators that reference the constant action types.