React-Redux Actions and Action Creators

Adwaith KS
2 min readMar 5, 2022
Credits: Lautaro Andreani (unsplash.com)

Let’s get straight into it, Redux action, is just a plain javascript object. Yes! you heard it right. It is just a plain javascript object which describes some kind of action.

Now, what is an action?

For example, Suppose a user wants to edit his/her username in the website. For that, he/she types in, the new username in the username edit section, and clicks the update button. This is an action! The user has just set his username to a new value.

Now the way we represent this action, using a javascript object, is called a Redux action, and it looks something like this:

Javascript

const setNewUsernameAction = {
type: 'USERNAME_TYPE',
payload: new_username
}

The above setNewUsernameAction object contains 2 attributes: type and payload. The type attribute represents a name for that action, and the payload represents the new username that the user has given. (type and payload is just a naming convention, you can use any name instead of type and payload. But, stick to conventions!)

Now, in order to avoid writing this action object by hand every time when dispatching actions (in simple terms, dispatch means triggering an action), for developer experience, we can use something known as Action Creator.

Action Creators

It simply means, you enclose the action object inside a function, so that, when you can call this function, the function returns you with the action object. Technically, it is a function that creates and returns an action object.

Example:

const setNewUsername = (new_username) => {
return {
type: 'USERNAME_TYPE',
payload: new_username
}
}

setNewUsername function returns us the action object with payload field set to new_username(username you provided as argument). Now you just need to dispatch an action called setNewUsername with the new username as an argument (as updated by the user in website).

Something like this:

dispatch(setNewUsername(‘adwaithks’));

What if you didn’t use an action creator?

You will have to dispatch the action like this:

Javascript

dispatch({
type: 'USERNAME_TYPE',
payload: new_username
})

Which one is easier and more elegant? Of course the dispatch where we used action creators instead of plain actions, right?

That’s it! Now you know what is an action and action creator in React-Redux.

--

--

Adwaith KS

Cyber security enthusiast | Part time Bug bounty hunter | MERN stack