Skip to main content

Redux Actions and Action Creators (Part 2): A Practical Example #108

📖 Introduction

Following our introduction to Redux actions and action creators, this article provides a practical, hands-on example of how to use them in a React application. We will build a simple to-do list application to demonstrate how to create actions and action creators, and how to dispatch them from a component.


📚 Prerequisites

Before we begin, please ensure you have a solid grasp of the following concepts:

  • All concepts from Part 1 of this series.
  • How to set up a Redux store and connect it to a React application.

🎯 Article Outline: What You'll Master

In this article, you will learn:

  • Creating Action Types and Creators: How to define action types and create action creators for a to-do list application.
  • Dispatching Actions: How to dispatch actions from a React component to update the Redux store.
  • Practical Application: Building a simple to-do list application that uses Redux actions and action creators.

🧠 Section 1: The Core Concepts of a To-Do List with Redux Actions

In a Redux application, all state changes are initiated by dispatching actions. For our to-do list, we will need actions for:

  1. Adding a to-do item.
  2. Toggling the completion status of a to-do item.

We will create action creators for each of these actions to make our code more readable and maintainable.


💻 Section 2: Deep Dive - Implementation and Walkthrough

Let's build our to-do list application.

2.1 - The actionTypes.js File

First, let's define our action types.

// actionTypes.js
export const ADD_TODO = 'ADD_TODO';
export const TOGGLE_TODO = 'TOGGLE_TODO';

2.2 - The actions.js File

Now, let's create our action creators.

// actions.js
import { ADD_TODO, TOGGLE_TODO } from './actionTypes';

let nextTodoId = 0;

export const addTodo = content => ({
type: ADD_TODO,
payload: {
id: ++nextTodoId,
content
}
});

export const toggleTodo = id => ({
type: TOGGLE_TODO,
payload: { id }
});

2.3 - The todos.js Reducer

Let's create a simple reducer to handle these actions.

// reducers/todos.js
import { ADD_TODO, TOGGLE_TODO } from '../actionTypes';

const initialState = {
allIds: [],
byIds: {}
};

export default function(state = initialState, action) {
switch (action.type) {
case ADD_TODO: {
const { id, content } = action.payload;
return {
...state,
allIds: [...state.allIds, id],
byIds: {
...state.byIds,
[id]: {
content,
completed: false
}
}
};
}
case TOGGLE_TODO: {
const { id } = action.payload;
return {
...state,
byIds: {
...state.byIds,
[id]: {
...state.byIds[id],
completed: !state.byIds[id].completed
}
}
};
}
default:
return state;
}
}

2.4 - The AddTodo Component

Now, let's create a component that allows us to add new to-do items.

// components/AddTodo.js
import React, { useState } from 'react';
import { useDispatch } from 'react-redux';
import { addTodo } from '../actions';

function AddTodo() {
const [input, setInput] = useState('');
const dispatch = useDispatch();

const handleAddTodo = () => {
if (input.trim()) {
dispatch(addTodo(input));
setInput('');
}
};

return (
<div>
<input
onChange={e => setInput(e.target.value)}
value={input}
/>
<button onClick={handleAddTodo}>Add Todo</button>
</div>
);
}

export default AddTodo;

Step-by-Step Code Breakdown:

  1. useDispatch: We use the useDispatch hook from react-redux to get the dispatch function.
  2. dispatch(addTodo(input)): When the "Add Todo" button is clicked, we call dispatch with the result of our addTodo action creator.

💡 Conclusion & Key Takeaways

In this article, we've built a practical example of how to use Redux actions and action creators in a React application. We've seen how to define action types and creators, and how to dispatch actions from a component to update the Redux store.

Let's summarize the key takeaways:

  • Actions are the only way to get data into the Redux store.
  • Action creators make your code more reusable and easier to test.
  • The useDispatch hook is used to dispatch actions from a React component.

Challenge Yourself: To solidify your understanding, try to create a TodoList component that displays the list of to-dos and allows you to toggle their completion status by dispatching the toggleTodo action.


➡️ Next Steps

You now have a solid understanding of how to use Redux actions and action creators. In the next article, "Redux Reducers (Part 1)", we will take a deeper dive into reducers and learn how to handle more complex state updates.

Thank you for your dedication. Stay curious, and happy coding!


glossary

  • useDispatch: A hook provided by react-redux that returns the dispatch function from the Redux store.

Further Reading