Simplify a Component Reducer with the React setState Hook

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

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

Instructor: [00:00] 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.

[00:11] 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.

[00:27] 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.

[00:46] 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.

[01:06] 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.

[01:18] 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.

[01:31] 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.

Gautham Stalin
Gautham Stalin
~ 5 years ago

Didn't see the setState coming. Great tutorial!!

Srinivas  Kasiriveni
Srinivas Kasiriveni
~ 5 years ago

Great tutorial!!

Ajay Kumar
Ajay Kumar
~ 5 years ago

Magic of logical thinking !.

~ 5 years ago

Very elegant, great one Kent

Markdown supported.
Become a member to join the discussionEnroll Today