02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Introduction to Redux Actions: Creating Action Methods and Best Practices

Introduction to Redux Actions: Creating Action Methods and Best Practices

In this tutorial, we'll dive into the basics of creating Redux action methods, extracting them for better organization, and implementing best practices to make your Redux workflow smoother and more efficient.

Understanding Redux Actions

Redux actions are plain JavaScript objects that describe changes to the application's state. Actions are the only way to communicate with the Redux store. To make your Redux code organized and easier to manage, it's a good idea to extract action logic and use action creators and bound actions.

Action Methods and Action Creators

An action method, or action creator, is a function that returns an action object. Instead of writing action objects manually each time you want to update the store, you can use action creators to ensure consistency and reduce repetition.

For example:

// actionTypes.js
export const ADD_COUNTER = 'ADD_COUNTER';

// actions.js
import { ADD_COUNTER } from './actionTypes';

export const addCounterAction = () => ({
    type: ADD_COUNTER
});

In this example, addCounterAction is a simple action creator that returns an action object. This keeps our code modular and reusable.

Bound Action Creators

Bound action creators automatically dispatch the action they create. They can be useful when you want to connect action creators directly to components, reducing boilerplate.

Here's an example:

import { addCounterAction } from './actions';
import { useDispatch } from 'react-redux';

const MyComponent = () => {
    const dispatch = useDispatch();

    const handleAddCounter = () => {
        dispatch(addCounterAction());
    };

    return (
        <button onClick={handleAddCounter}>Add Counter</button>
    );
};

In this example, dispatch(addCounterAction()) automatically sends the action to the Redux store. This is what we mean by "binding" the action creator.

Extracting Logic from Components

When building applications, it is beneficial to keep Redux-related logic separated from your UI components. This keeps your components focused on presentation rather than state management, which makes them more reusable and easier to test.

For instance, you might have a component that currently handles both UI and business logic like so:

const Counter = ({ counter, incrementCounter }) => {
    return (
        <div>
            <p>Counter: {counter}</p>
            <button onClick={incrementCounter}>Increment</button>
        </div>
    );
};

To make this component more reusable and decoupled from Redux, you can extract the logic for incrementing the counter and keep the component focused only on the UI.

Moving Logic to a Separate File

  1. Create an Actions File: Create a new file called actions.js in your store directory to hold your action creators.

  2. Extract Business Logic: Extract any business logic from your components and put it into functions in the actions.js file.

  3. Keep Components Clean: Use these action creators within your components without embedding the logic directly into the components.

Example:

// actions.js
export const addCounter = () => {
    return {
        type: 'ADD_COUNTER'
    };
};

// CounterComponent.js
import { useDispatch } from 'react-redux';
import { addCounter } from './store/actions';

const CounterComponent = () => {
    const dispatch = useDispatch();

    const incrementCounter = () => {
        dispatch(addCounter());
    };

    return (
        <div>
            <button onClick={incrementCounter}>Increment Counter</button>
        </div>
    );
};

Benefits of Extracting Logic

  • Reusability: UI components can be reused more easily when they are not tightly coupled with the logic.
  • Testability: It is easier to write unit tests for components that are focused purely on rendering.
  • Readability: Extracting business logic into actions and separate files makes your codebase easier to read and maintain.

Handling Bound and Unbound Actions

The distinction between bound and unbound actions is crucial. Bound actions are used to dispatch actions automatically, whereas unbound actions are primarily used for creating the action object but require you to explicitly call dispatch() to execute them.

In a more complex scenario, the need to manipulate data before dispatching arises. For example, you may need to validate data or fetch additional information before creating an action. Separating actions and dispatch makes it easier to handle such cases.

// actions.js
export const addCounterAction = () => ({
    type: ADD_COUNTER
});

export const addCounter = () => {
    return (dispatch) => {
        // Add any logic before dispatching
        dispatch(addCounterAction());
    };
};

This approach ensures that your logic is encapsulated within the addCounter function, while the actual action creator (addCounterAction) remains pure and simple.

Summary

  • Action Creators: Create functions that return action objects to keep code consistent.
  • Bound Actions: Bind actions to automatically dispatch them.
  • Extract Business Logic: Keep Redux logic outside of UI components for better maintainability.
  • Bound vs Unbound Actions: Know when to use each type to handle scenarios that require more complex data manipulation.

By following these practices, you'll create a scalable Redux store and build maintainable React applications that separate logic and presentation effectively.

Next Steps

In the next part of the series, we'll continue to explore how to handle more advanced Redux scenarios, such as actions with payloads and creating more complex state updates that integrate well with our React components.

Video Transcript

00:00So this lecture is gonna be all about actions.
00:03And the first part we're gonna talk about action
00:05methods and create them.
00:06And really the idea itself is a, a method that will
00:10generate a object for us that is an action.
00:13And we're also gonna look at how
00:14to create bound action methods, which are very,
00:16very convenient and I find them to be very, very useful.
00:19So let's jump right into it.
00:22Alright, so our main goal, as you probably started
00:25to notice, is to extract out of our react components,
00:29business logic or any logic really related to manipulating
00:32and working with directly with Redux and its actions.
00:37So currently right now we have a few actions going on
00:40and among them, for example, in our application itself,
00:43we have here an add counter.
00:45What I would like to do is to take this add counter logic
00:48and literally extract it out.
00:50So I'm just gonna grab this a add counter,
00:53and I'm just gonna go ahead into our,
00:54a new file called Actions js, which is gonna be located
00:58inside of our store.
00:59I'm also gonna need to make sure that I import my types.
01:02So let me go ahead and just grab the same import
01:06that we've done inside of the store.
01:08Oh, inside of our store itself.
01:10I'm gonna do that also for our actions only.
01:12This time relatively speaking, I don't need to
01:15have the directive of store anymore
01:17because it's gonna be much closer.
01:20So we're creating this new, uh, ad counter,
01:22but this new ad counter, by the way,
01:24we wanna do it a little bit differently.
01:26For one actions, generally speaking in the convention
01:29of the creators of the library
01:31are separated from the actual dispatch itself, contrary to
01:36how it is done in React.
01:38So what we could do is, for example, uh,
01:40we could create here an add counteract action.
01:50Now, our ad count counteract action,
01:51and I'm literally calling it explicitly calling it action.
01:54So I'm very aware that this is what it does.
01:56Doesn't really accept any parameters in our case,
01:59but what it does is it returns a specific object,
02:02which is this specific object.
02:05Now in, in our case,
02:06there's really no logic in separating it
02:09because anytime we want to create an action,
02:11we wanna create also a dispatch of that action.
02:14But in a real world scenario, that's not always the case
02:18because a lot of times in a real world scenario,
02:20we might want to manipulate this data
02:22before we continue onwards.
02:24So it's not a bad idea to have a add counteract action.
02:26I'm gonna export it
02:27and I'm also gonna export our, let's call this function
02:34And we wanna export our ad counter.
02:36Now I'm gonna go ahead and also import our store itself,
02:39which we'll get from our store, uh, from dot,
02:43dot back store.
02:45And let's continue. Okay, so we imported our store
02:48and let's following through.
02:50We have here in action
02:51that is literally just returning an object of an action.
02:54While we have here a dispatch
02:56or a bound action that is actually going to,
02:58anytime we call the add counter,
02:59it should then dispatch this event.
03:02So let's go ahead and also connected.
03:03So I'm gonna go into my app itself
03:05and instead of using this add counter
03:07that I have right here, I'm gonna go ahead and delete it
03:10because instead of that, what we're gonna go ahead
03:12and do, we don't need the store anymore,
03:13but instead of that we're gonna go ahead
03:15and load in that specific action.
03:18And after we've loaded that action,
03:20I'm gonna literally go ahead and send in that action.
03:23Instead of this count add counter,
03:25I'm just gonna call the add counter,
03:27which will be bound to it.
03:28So although we're still using very explicit things from
03:33Redux, it doesn't really know it's from Redux
03:35within our component.
03:37Thus, if we change our data source
03:39and we're gonna use a different data source,
03:41it doesn't really need to know how
03:42that data source works from within.
03:44All it needs to know is that this needs to take care of it.
03:47So if we go ahead and just check
03:48to see if we have any errors, so we have your one failure,
03:51let's see what that failure is.
03:53It cannot find store and that is
03:55because we need to take a two step back.
03:57I believe. Let's see, where, where was that error?
04:01Um, store, app store. No, that's good.
04:05Action is good 'cause it's actions and a plural.
04:09Okay, and let's check again. Beautiful.
04:12We passed the test and if we try to now add more counters,
04:16our counters should add without any problem.
04:20In this lecture, we introduced ourselves to action functions
04:24or really, uh, functions that return in action
04:26and functions that trigger a dispatch of an action itself.
04:31In the next lecture, we're gonna continue down this path
04:33by continuing to extract our actions this time
04:36around actions that have properties.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!