Current section: State Optimization 36 exercises
Problem

Optimize state updates

Loading exercise

Transcript

00:00 All right. So we've got something that's a little suboptimal in here. We put some console logs in our code so that we can know when certain things happen. So we're re-rendering the component for the new query. So we're initializing our components. We get a re-render there. And then if I submit right here, that's

00:18 just setting this state in our history. So now we're setting the search params and re-rendering again. That wasn't really necessary, though, because we didn't need to re-render. There was no change in the state. So that's kind of interesting. If I go to dog and then submit that,

00:36 we're getting a re-render every single time I do that. But we're not actually really changing much. So then if I go back, you'll notice that the dog query actually didn't change because that's what we were committed to before. But we're re-rendering anyway. And then we go back again. And that should re-render because that did actually

00:55 change the UI a bit. So we are getting some re-renders that are necessary, others that are not. And we just want to optimize things so that we don't update the state when nothing actually ends up changing. So in the places where we're setting our search params, because that's how we're deriving our search query.

01:14 So we're storing the search params in state. And when we go and update those, we want to check whether the search params actually are changing. And if they are changing, then we'll go ahead and update with the new version of the search params. If they're not, then we should return the old ones.

01:31 And that will help us avoid re-rendering unnecessarily. So just a little optimization here. Let's get to it.