learnreact.com is moving to school.reactpatterns.com. Get 50% off while we move.

Learn React

Learn React | <!-- -->Essetial React<!-- --> > <!-- -->setState - functional form

Essetial React

setState - functional form

So we have our class clap component. It sets an initial state, which is an object in claps with a value of zero that renders out this little button that shows our zero and the hand that say that when we clap it, it’s going to add claps. Now that works the first time because we’re using setState with this object form where we replace, or merge in the values that we care about. But our button doesn’t work any subsequent times that we press it. It always just changes it to one, because we’re hard coding it here. What we really want is to infer from this previous state the next value, and we do that with a second form of setState, which is the functional form. Now this functional form, instead of passing an object in, sends in a function. That functions receives the previous state as an argument and then uses that argument to return a new object. That object uses the property that we’re interested in changing, and then grabs that value off of the previous state, and transition it in some way. In this case we’re going to add one to it. Now when we click our button, it transitions from zero to one, from one to two, from two to three, and so on. No this form can be a little tricky to parse, so what I want you to realize is that the end result is, again we’re just returning this object. It’s very similar before, where we’re returning an object with a new claps value. But we need a way of knowing what the previous claps value was, and we do that by wrapping this whole thing in a function that takes that previous state as an argument when called. Now this can be a little tricky to understand, so I’m going to cover the concept in more depth, but for now I’d actually like to change the syntax a little bit so it mirrors more the modern style that you are likely to see. We can remove this function keyword and replace it with this arrow. At this point it still works, and then we can take away this block and return and replace it with this more terse parentheses.And again, the whole thing still works. So we’re still doing the same thing, we have an anonymous function that returns an object that transitions the claps value using the previous claps, plus one.

Keep in touch!

Get notified of new React content and resources

    We respect your privacy. Unsubscribe at any time.