I suggest we call these reducer bundles “ducks”, as in the last syllable of “redux”.
Duck born in context of how improve the folder structure in a Redux application. Out there, the first discussion that you will find, will be Folder-by-Type vs Folder-by-Feature as we can see in the next example:
(Folder by type in the left side, and by feature in the right side)
As you can see, folder by type it doesn’t scale well in medium-large applications. In the other hand, by feature, seems that make sense gathering related content together to foment the modularity, portability (we could export easier to other project if we don’t have much dependency with others modules) and scalability. But, we are still coupling our UI library (React) with our state management (Redux).
Ideally, at design level, we always we want to increase the cohesion and decrease coupling things together.
Ducks, give us some rules to help us to following this principle.
A Module (actionType, action, reducer) should be structure in the following way:
- MUST declare
export defaulta function called
exportits action creators as functions.
- MUST have action types in the form
- MAY export its action types as
UPPER_SNAKE_CASE, if an external reducer need to listen for them, or if it is a published reusable library.
That will help us a lot in terms of scalability in medium application, but if our applications, keep growing we will realize that a single file for a feature will become like spaghetti file code as well. In that point the next solution born, named Re-Ducks.
The main different between Re-Ducks and Ducks is about instead of use a single Duck file we move into separate folders. In that way your structure folder should look like the following way:
As we see, now we have a root
ducks/index.ts and one dock two docks named
ducks/index.ts looks like:
catalog dock looks like:
So, as you can see, as a default we will export our
reducer . And then the
stateSelectors will be exported in a non default way.
Then we will have access from them in the view:
And the root reducer could be imported in our
store.ts as we can see in the following image:
I hope, you are following me about the benefit and powerful about this great structure proposal!