Autoplay

    Redux: The Reducer Function

    Dan AbramovDan Abramov

    There is something in common between all Redux applications. They have to implement the reducer: a function that calculates the next state tree based on the previous state tree and the action being dispatched.

    We are presenting a “complete” example in the code window below. Feel free to click around and explore! We will be explaining what everything does during this course.

    reactReact
    0.14 -16
    reduxRedux
    3 - 4
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 You might have heard that the UI or the view layer is most predictable when it is described as a pure function of the application state. This approach was pioneered by React but is now being picked up by other frameworks, such as Ember and Angular.

    00:17 Redux complements this approach with another idea, that the state mutations in your app need to be described as a pure function that takes the previous state and the action being dispatched and returns the next state of your application.

    00:36 Inside any Redux application, there is one particular function that takes the state of the whole application and the action being dispatched and returns the next state of the whole application. It is important that it does not modify the state given to it. It has to be pure, so it has to return a new object.

    00:59 Even in large applications, there is still just a single function that manages how the next state is calculated based on the previous state of the whole application and the action being dispatched. It does not have to be slow.

    01:16 For example, if I change the visibility filter, I have to create a new object for the whole state, but I can keep the reference to the previous version of the todos rate, because it has not changed when I changed the visibility filter. This is what makes Redux fast.

    01:35 Now you know the third and the last principle of Redux. To describe state mutations, you have to write a function that takes the previous state of the app, the action being dispatched, and returns the next state of the app. This function has to be pure. This function is called the "Reducer."

    Discuss

    Discuss