Structuring Reducer Logic for Features
We'll cover the following...
As mentioned previously, we’re using a “feature-first” folder structure. There’s tradeoffs with both “file-type-first” and “feature-first” approaches.
With “file-type-first”, you know where to look for a certain type of code, and it’s really easy to pull together all the slice reducers into a root reducer file. However, each feature gets split across several folders, and if multiple features need to interact with a specific slice of state, the files or folders for that slice of reducer logic will start to get awfully crowded.
With “feature-first”, you know exactly where all the files for a given feature are, but the process of combining the reducer logic together can be a bit tricker, especially if you’re using the standard approach of combineReducers
. In particular, what happens when multiple features need to interact with the same slice of state?
In our case, we’ve created an entities
slice containing the “tables” for our relational data entries. Because this is a central data location for our application, several different features are going to need to make updates to the entities
slice. We could put all the reducer logic from the different features together into one giant entitiesReducer
, but that would get ugly rather quickly. What we really need is a way for each individual feature to separately apply updates to the entities
slice.
Looking Beyond combineReducers
I’ll paraphrase some of the key concepts from the Structuring Reducers section of the Redux docs:
It’s important to understand that your entire application really only has one single reducer function: the function that you’ve passed into
createStore
as the first argument. It’s good programming practice to take pieces of code that are very long or do many different things, and break them into smaller pieces that are easier to understand. Since a Redux reducer is just a function, the same concept applies. You can split some of your reducer logic out into another function, and call that new function from the parent function.In Redux it is very common to structure reducer logic by delegating to other functions based on slice of state. Redux refers to this concept as “reducer ...