React and TypeScript React and TypeScript

useEffect TypeScript Solution

Check out a free preview of the full React and TypeScript course:
The "useEffect TypeScript Solution" Lesson is part of the full, React and TypeScript course featured in this preview video. Here's what you'd learn in this lesson:

Steve live codes the solution to the useEffect TypeScript exercise.

Get Unlimited Access Now

Transcript from the "useEffect TypeScript Solution" Lesson

[00:00:00]
>> Our mission right now is to debug a red squiggly, right? Which is kind of a rite of passage in working in a TypeScript application. All right, so number is not assignable to type void, returning either void or undefined, okay? So what do we need to do here, right?

[00:00:25] Well, it turns out that useEffect is expecting a function signature that returns undefined. SetTimeout and setInterval return numbers, which are usually an identifier for clear interval, you would need the number. So really, because we're using the immediately returning arrow function, we accidentally passed in the wrong value, and TypeScript's built-in React types, or the React types that you install with TypeScript, with React rather, caught that.

[00:00:55] So adding the curly braces will make sure that we're not passing in code that we didn't intend to pass in. Now, in this case, no harm, no foul, right? But it's one of those things which is like, right? This accidentally did a thing I wasn't expecting. And again, having that programmatic ability to analyze your code and find all of these small bugs will go through and add reliability to code, hopefully confidence, as you become more comfortable with TypeScript.

[00:01:31] There's allegedly a study that shows using type checking, whether it's TypeScript or Flow, reduces the number of bugs 15%. I believe it. I have questions on the methodology, cuz how do you know about the bugs you didn't find, right? But generally speaking, the worst bugs are the very simple ones that didn't seem obvious at the time, and you've gotta kinda suss them out and find them, not at the most opportune time.

[00:02:01] So having somebody that's gonna analyze your code, find all the things where your code is behaving just a little bit differently than you might expect, I think is incredibly helpful. All right, this whole time, we've been living in the modern era, right? We've been using functional components and hooks everywhere.

[00:02:18] But I don't know about the rest of you. One thing in the chat is useEffect can take a cleanup function if it needs a cleanup function, but that is an optional value. That's why, theoretically, we can have a second function in the type signature.