State Management in Pure React, v2 useEffect Solution
This course has been updated! We now recommend you take the React Performance course.
Transcript from the "useEffect Solution" Lesson
>> All right, so let's take a look at this now. So we can say for useState, we want to get that initial value out of there. So we'll go ahead and we'll say, getStateFromLocalStorage will be our initial value. Verify that that works. Right, because I decrement, I refresh, was just putting back to 15 because that's from our previous example what I happen to have in local storage.
[00:00:25] So we can verify that we are in fact reading it from local storage. Now to register an effect, we can actually just put a second one here. We can say useEffect. And we'll say, storeStateInLocalStorage. We'll give it that count. Again, because it's using count, it needs to have the count in there as its dependency.
[00:00:50] So now whenever the count changes, we'll automatically store it in local storage and we don't have to think about it anymore. We'll decrement, I'll refresh. It is saved in local storage. So you're like, this is great. I want to do this all the time. I'm into it, right?
[00:01:10] But you can see that as you add this stuff in here, it could get a little tricky. And one of the things that I kind of want to point out is these hooks are just functions, right? And so we've combined two already. This idea of setting and using state and this idea of using effects to update the document title, to update local storage.
>> Quick with the useEffect. We're doing that twice with same dependency, is that-
>> I mean, I could-
>> Just as an example would, you-
>> I could put two of them in here as well.
>> So you'd normally split it out based maybe on what the dependencies are for each effect?
>> Maybe. Right, in this case it was to kind of keep them separate. I'm about to refactor out, use local storage as its own.
>> Right, so in that case, I need them separate. Cuz I know that I'm gonna refactor it. But could you theoretically do this as well?
>> Right, I would imagine if you got really carried away, you could take it to its natural conclusion, create a performance problem. But I challenge you to measure that one and find it before we actually call it out as never do those kind of things.
>> You trade off the creation and invocation of an additional function over modularity, right? And so it's like, do you want an architecture that you can sustain? Or do you want the nanoseconds performance? And I'm not saying that that was a softball question. Sometimes you need those nanoseconds of performance.
[00:02:33] And sometimes you need the architectural tradeoffs. We'll actually see that in the next app. We'll do something. We'll optimize for performance. Then we'll optimize for our sanity and undo our performance optimizations. So that is a real question, and the answer is always, it depends. Which is really unsatisfying.
[00:02:51] But again, here we are.