Current section: useEffect 16 exercises
solution

Implementing Your Own useEffect

Transcript

00:00 Let's start out by deleting the built-in useEffect. Let's also bring in flushSync, which we'll need here in a bit. Let's make our bucket of effects. So effects is an array of objects that have a callback property. And with that now, we can store those.

00:16 So every time useEffect is called, we're going to store this callback in that bucket of effects. So let's make our useEffect. This will take a callback, which is an effect callback. And then we get our ID from the hook index. And no, we're not going to push it on the effects array.

00:33 Instead, we want to put it into effects at that ID, so that we always make sure we're keeping those effects up to date, so as the callback changes or whatever. Okay, great. So then the last thing we're going to need to do is come down here to our render.

00:51 Whoops, we don't need to make a function. We're going to wrap it in a flushSync function. And what this will do is it will say, hey, React, I know that you like to do your batching, and you like to make things as optimal as possible, whatever. I need you to just run this synchronously. This is as good as we can do not being React.

01:10 And so we're going to say, React, run everything synchronously. And that way, our effect callbacks get added to the effects. And actually, I'll just demonstrate really quick what happens if we don't do that. So if I console.log the effects at this point, after the flushSync,

01:26 then you'll notice we have our effect at index 2. And so that is awesome. But without the flushSync, then we have an empty array in this case. And that's because React is doing things as optimally as possible to not block the main thread of the browser.

01:44 So we are kind of de-opting out of that a little bit for our purposes so that we can iterate over these effects and call them all and all that stuff. So we'll do a forof loop to get an effect of the effects. If there is no effect, then we'll simply continue.

02:03 That way we don't, you'll notice we do have some empty items and stuff like that. We can have some problems. So we're just going to only call the effect callback if that effect exists. And now consider yourself effective. We are totally doing that. Awesome. Let's get rid of that log there as well.

02:21 And boom, every time we get a render, we're going to get that called. So there you go. We have effects done by creating this bucket of effects. We have our useEffect right here where we get the ID from the hook index. And we set that ID in the effects to be this object with the callback.

02:40 And then we flush the render so that it happens synchronously and iterate over the effects to call them if they exist. There you go.