Implement Component State Reducers

InstructorKent C. Dodds

Share this video with your friends

Send Tweet

Often with reusable components, the logic needs to be adjusted to handle various use cases. Rather than filling our component event handlers with if statements and loading our state with one-off properties, we can expose our state directly to users of our reusable component in a way that's flexible and simple with a state reducer.

Viktor Soroka
~ 6 years ago

Nice. Why do you need state argument in the toggleStateReducer if you do not use it?

Kent C. Doddsinstructor
~ 6 years ago

Hi Viktor, The Toggle example that we're using in this course is great, but it's not entirely practical. In a more real-world component, having the state can be useful. For example, some of the examples here use a state reducer (you can see the state reducers in the shared.js file) and one of them references the state: https://codesandbox.io/s/924217jvro

Viktor Soroka
~ 6 years ago

Thanks for that.

Thein
~ 6 years ago

state argument in the toggleState reducer is called from toggle Component and not useful for Switch Component. The properties associated in that state are from toggle component.

Bogdan Bivolaru
~ 6 years ago

Hi Kent, Could you explain where timesClicked is stored - console does not print this somehow? I am trying to show timesClicked in console from handleToggle:

handleToggle = (...args) => {
    this.setState(mystate => {
      console.log(mystate)
      let {timesClicked} = mystate
      return {
        timesClicked: timesClicked + 1,
      }
    })
    this.props.onToggle(...args)
  }```
 (https://codesandbox.io/s/rwp5z49qo4)
Kent C. Doddsinstructor
~ 6 years ago

console does not print this somehow?

It seems to be printing it fine for me. You can learn more about the state updater function in the setState docs. I hope that's helpful.

Bogdan Bivolaru
~ 6 years ago

Thanks for your input, I'm not sure what I did the other day that broke things.

Matthias Hryniszak
~ 6 years ago

You know, I may be somehow hindered but it all seems overly complex to do something so simple. I know react is all about functional programming (and this might be my disability to do FP proficiently) but still - introducing a new API for setting the state seems like the worst thing to do because it defies the least-surprise principle.