Alvaro Maceda
Alvaro Maceda

Reputation: 614

Why are Redux actions implemented as functions?

I'm studying how Redux works, and there is something I can't fully understand.

Usually Redux actions are implemented as functions. For example:

const ACTION_INCREMENT = 'INCREMENT'
const increment = function(amount) {
   return {type: ACTION_INCREMENT, amount: amount}
}

store.dispatch(increment(2));

Why aren't action implemented as classes? I mean, I find more natural something like this:

class ActionIncrement {
    constructor(amount) {
      this.amount = amount;
    }
}

store.dispatch(new ActionIncrement(2));

It's very strange that nobody does this. Is there an issue with this approach I haven't seen?

Upvotes: 1

Views: 106

Answers (2)

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

I will suggest reading the Motivation section in the documentation.

Following in the steps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.

You could create Classes as they are just syntactic sugar for creating Objects, however, what would be the benefit of doing that over more explicit Object literal?

An action is a simple configuration object with no side-effects which gives a lot of benefits like time-travel and more predictable debugging which is one of the main advantages of using redux. Having Classes IMO besides introducing extra code could point people to creating some state-mutating functionalities.

Upvotes: 1

Roy Wang
Roy Wang

Reputation: 11260

What you are referring to are action creators, which are functions that return actions (JS objects).

Here are some disadvantages I can think of right now:

  • Classes are syntactically more complex, leading to longer boilerplate code, more room for misuse/mistakes (eg. forgetting to assign a type property for the reducers to identify).

  • Action creators are meant to be stateless. Using classes might lead to more misuse/misunderstanding. Granted, you can use this on functions as well, but that's less common (and not possible for functions declared with ES6 arrow syntax).

  • It will be incompatible with many existing Redux libraries, such as redux-thunk. redux-thunk delays the dispatching of the action to the reducers, allowing asynchronous calls in action creators. For such libraries to support classes, all classes must agree to have a common async method that will be called and awaited. This leads to more boilerplate and room for misuse/mistakes.

Upvotes: 2

Related Questions