Hooks 11 exercises

Properly use the useEffect API

Here's the error message we had:

Type 'Timeout' is not assignable to type 'void | Destructor'

To understand what it means, let's take a look at the useEffect function to see what Destructor means.

Examining useEffect's Types

Use the CMD + Click shortcut on the `useE

Loading solution


0:00 Let's break down this error first. What's happening here is Type Timeout is not assignable to type void or Destructor. Let's actually take a look at useEffect itself to see what Destructor means.

0:12 We command-click into here. You can see that we've got a function inside here that says, "useEffect" and "effect EffectCallback" and "deps DependencyList." The way that these types tend to work is they tend to use aliases for a lot of different things.

0:28 If we command-click, look at DependencyList, then we can see it's a ReadonlyArray of unknown. Basically, any array can be passed into here. That's good.

0:38 Next, we want to look at the EffectCallback. EffectCallback is the thing that you're passing into the first argument of useEffect. Let's command-click to there. This is basically a function which has no arguments and can either return void, so nothing, or it can return a Destructor. A Destructor looks like this. We have a function that also returns void.

1:00 I'm actually not sure what this UNDEFINED_VOID_ONLY never...I'm really intrigued by that. I'm actually not sure what it does, but we have a Destructor type here. That means that this Destructor type, if we look at this, this function is expecting to return either void or another function.

1:18 Let's just make it return void for now. Let's wrap it in some curly braces. Now, our type error goes away. If we don't return anything from here, then it's actually going to be quite happy.

1:28 The thing we can return...We can't return a number, for instance. We definitely can't retrurn it. We can't return a number because it's expecting it to be an EffectCallback or void. An EffectCallback looks like this.

1:42 Now, everything's happy. Now, we can start to think, "OK. What is it that we actually want to do with this timeout?" We know that when you set a timeout, you will eventually want to clear it because if you don't clear it, you're just going to have oodles of these timeouts running.

1:57 What we can do, we can say, "const timeout = setTimeout." Then, inside the EffectCallback, we can return clearTimeout timeout. This is just a way to introduce you to the basics of useEffect's API and also show what it will accept and what it won't accept.

2:13 useEffect is one of the rare hooks in React that isn't generic. I just wanted to add this in here so that you can understand the kind of language it uses in its API when it's describing effect and useEffect and the DependencyList.