1. 15
    Redux: Reducer Composition with combineReducers()
    2m 10s

Redux: Reducer Composition with combineReducers()

Dan Abramov
InstructorDan Abramov

Share this video with your friends

Send Tweet
Published 7 years ago
Updated 2 years ago

Learn how to use combineReducers() utility function to generate a reducer from several other reducers instead of writing it by hand.

[00:00] In the previous lesson we learned how to use the reducer composition pattern to let different reducers handle different parts of the straight tree, and then combine their results.

[00:13] This pattern is so common that it's present in most Redux applications. This is why Redux provides a function called combineReducers that lets you avoid writing this code by hand. Instead, it generates the top level reducer for you.

[00:31] The only argument to combine reducers is an object. This object lets me specify the mapping between the straight field names, and the reducers managing them. The return value of the combineReducer is called a Reducer function, which is pretty much equivalent to the reducer function I wrote by hand previously.

[00:53] The keys of the object I configure combined reducers with correspond to the fields that the straight object is going to manage. The values of the object I have asked to combineReducer, are the producers we should call to update the correspondence straight fields.

[01:14] This combineReducer call says that the ToDo's field inside the straight object managers will be updated by the reduce-reducer, and the visibility filter field inside the straight object will be updated by calling the visibility filter reducer. The results will be assembled into a single object. In other words, it behaves pretty much exactly as the function commented down below.

[01:41] Finally, I will establish a useful convention. I will always name my reducers after the straight keys they manage. Since the key names and the value names are now the same, I can omit the values thanks to the ES6 object literal shorthand notation.

[02:00] In this lesson, you learned how to generate a simple reducer that calls many reducers to manage parts of its tree by using the combineReducers utility function.

~ 7 years ago

Can we use combineReducers() several times in the "nested" reducers or is it just here to create the top level reducer ?

Dan Abramov
Dan Abramovinstructor
~ 7 years ago


You can absolutely use combineReducers() multiple times. In fact "shopping cart" example in Redux repo does that.