Reducer Nesting and Coupling
Here we pass action through multiple reducers and discuss the best approach to nesting.
Let’s try to implement a reducer that adds a new ingredient to a recipe. There are two main approaches:
- All the reducers in the chain are aware when the action is passed.
- Each reducer only passes the information down to its children.
We can implement the first approach as follows:
const booksReducer = (state, action) => {
switch (action.type) {
case ADD_INGREDIENT:
return Object.assign({}, state, {
books: state.books.map(
book => book.id !== action.payload.bookId
? book
: recipesReducer(book, action)
)
});
}
};
const recipesReducer = (book, action) => {
switch (action.type) {
case ADD_INGREDIENT:
return Object.assign({}, book, {
recipes: book.recipes.map(
recipe => recipe.id !== action.payload.recipeId
? recipe
: ingredientsReducer(recipe, action)
)
});
}
};
const ingredientsReducer = (recipe, action) => {
// Regular reducer
};
Get hands-on with 1400+ tech skills courses.