Image from Wikimedia Commons

I noticed that many Redux developers tend to organize actions by domains; that is; they split them in multiple files (and/or in multiple sub-folders). If you know any good reasons for doing that, please let me know. But right now I’m going to show you the benefits of putting them in one place.

1) You can write type-safe actions easily (without using any libs)

First, create an enum ActionType that can be used across your codebase.

Define all actions in enum

Once you have the ActionType enum, you can create a ActionPayload interface to define payload for each action.

Definition payload type of each action

The action creator below can protect you from using incorrect type and payload.

2) Infer payload interface in reducers.

You can use a typeguard function to infer payload interface given an action type. This is useful when you want to extract payload from an action in reducers.

3) Reduce boilerplate

Traditionally, for type-safety you may create an ActionCreator for each ActionType. But now you only need one action creator. See code below.

4) Prevent naming conflicts.

When you split actions into multiple places, there are no guarantees that you and your teammates define the same action types twice. By putting all action types into an enum, TS will force us to give each action type an unique name.

5) Code suggestions.

You just need to type “ActionType.” and your IDE (or code editor) can show you all available actions. Moreover, when you type “ActionType.DICTIONARY__”, you will see actions for DICTIONARY only.

Real world project:

We are using this method intensively in Ulangi open-source project. You can check it out here: https://github.com/ulangi/ulangi.

Here are the action files in project: ActionType, ActionPayload