Current section: useEffect 16 exercises
lesson

Introduction to useEffect

Transcript

00:00 So now that we have the ability to have multiple use state hooks, I think it would be good for us to try and implement another hook, useEffect. This one has a pretty simple API. It doesn't return anything. It has a callback. That callback can return a cleanup function.

00:15 And then it also has optional dependencies, which when those change is when the callback will be called. If there are no dependencies provided, then the callback will simply be called every single time. And one interesting thing about the callback is that it can return that cleanup function.

00:33 Unfortunately, we don't have an API in React to know when a component is getting unmounted. So we can't implement the cleanup function ourselves. Maybe some of you watching are creative and can figure out a way to make that work. But I couldn't, and so we're not going to go that far.

00:48 But we can ensure that our effects are run after React has finished rendering. And we do that by making React render synchronously. We're going to use the FlushSync API to tell React, hey, render this synchronously so that I have all my callbacks that I can then go through and call.

01:07 So we're going to implement this API. We're going to start out with no dependencies, and then we'll add dependencies. It's going to be a lot of fun, so let's get into it.