Current section: State Optimization 36 exercises
lesson

Intro to State Optimization

Loading lesson

Transcript

00:00 We're going to talk about state optimization a little bit. I referenced it a little bit in the previous exercise, but I want to really dial this in a little in this exercise. So the basic idea here is we have this use state, and it's initialized to zero.

00:15 And if the count is still zero, and we call set count to zero, React is going to see that and be like, oh, cool, you wanted to set the count to zero. Well, guess what? It already is. So the last React elements that you gave me should be exactly the same as the new ones, because the state didn't change. So I'm not going to bother. I'll just ignore this call.

00:34 The same thing happens with objects, whether you're using useReducer or useState. In the object case for useState, it's a little bit trickier, because you can't just pass zero again. This is a different object, and so it will trigger a rerender. So what you can do instead, and also the function form,

00:52 that will trigger a rerender, even though the properties are all the same. But what you could do instead is if you return the same thing that you're given, then that will not trigger a rerender, or if we were to pass state in here like this. But typically, you're going to use this optimization in the function form. You'll perform some sort of logic in here

01:12 and then determine, oh, actually, I don't need to do a state update. Just return the previous state, and you're all good. So that is what we're doing in this exercise. This should look a little familiar. Let's move on.