Current section: Side-Effects 29 exercises
Problem

Effect Cleanup

Loading exercise

Transcript

00:00 All right, so we've got a bit of a problem with our current solution with UseEffect, and that is we are not cleaning up properly. And this can cause minor problems, but it also can cause like pretty significant problems. So here with our UseEffect, we've got this callback,

00:14 and we are setting up our event listener. But if we don't return a function that removes the event listener, then we're going to hang on to all variables that were in scope at the time that this closure was created. And so anything that is inside of the UseEffect, all of the like

00:31 everything, everything that this function has access to or uses is going to be still hung on to by JavaScript in memory, even when the form or this component gets removed if we don't clean it

00:45 up. So it's important that we clean things up. So Kelly added this show form thing so that we can test this thing out a little bit, make sure that things are unsubscribing the way that they should. And if you really want to test some stuff out, then in the code, we've got some code blocks that

01:03 like creates an enormous amount of data in memory. And if you use the memory panel and read up a little bit on monitoring memory usage in the task manager, then you can actually watch the memory just climb and climb and climb every single time you check and uncheck this. So I would actually

01:21 recommend if you want to do that, to start with that, to see the problem first, and then go through the solution and then compare the before and after. It is pretty interesting. So have a good time with that.