Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Simplify a Component Reducer with the React setState Hook

    Kent C. DoddsKent C. Dodds

    Having a reducer is great for complex components but for our simple Stopwatch it’s a layer of abstraction that might not be necessary.

    We'll cover:

    • Converting your reducer into a function that shallow merges the new state into the old
    • Refactoring your dispatch function into setState


    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




    Instructor: Maybe for complex components having a separate reducer function for all of the state management is a useful idea, but for this simple stopwatch it seems to be a little bit of a layer of abstraction that may not be necessary.

    What we're going to do is we're going to simplify our reducer significantly by simply returning the state and the action. Instead what we're going to call this is the current state and the new state.

    We'll spread across the current state and the new state and effectively shallowly merging the current state with the new state, which is actually what setstate and class components is doing. We'll get rid of all this logic here and then every single one of our dispatches, we're going to actually rename this to setstate.

    When we dispatch here, we don't need to type anymore, we just need to have a state. We'll lapse is what we want to set, and that lapse is going to be the date minus the start time. When we dispatch this toggle running, what we can do is we can just say running is not running, and we'll call this setstate.

    Here we'll rename dispatch to setstate. Instead of a type of clear, we can say lapse of zero and running of false, and effectively is the same functionality as we had before.

    In review, all that we did here is we drastically simplified our component reducer in favor of putting a little bit of the logic for how this state should be updated directly into our component. This works really nicely for a simple component length like this one.

    We also renamed dispatch to setstate, so it could be made a little bit more clear what exactly is going on when we call that function.