02Geek HTML5 and JavaScript, TypeScript, React, Flash, ActionScript online School
Previous VideoNext Video

Building an Express Server

Managing Memory Leaks in React Applications

Memory leaks in JavaScript applications often result from unhandled events or timers. In this tutorial, you'll learn to identify, manage, and prevent memory leaks, especially when working with React.

Understanding Memory Leaks

  • Memory leaks occur when allocated memory is not released after it's no longer needed.
  • Common causes:
    • Events: Unremoved event listeners tied to DOM elements or objects that are no longer in use.
    • Timers: Intervals or timeouts that persist unnecessarily.

React's Role in Memory Management

  • React handles most memory management internally, especially when using component props and callbacks.
  • However, manual handling is required when:
    • Adding custom event listeners to the window or DOM elements.
    • Using setInterval or setTimeout in components.

Best Practices to Avoid Memory Leaks

  1. Add Events Responsibly:

    • Use lifecycle methods like componentDidMount to attach events when the component is mounted.
    componentDidMount() {
      window.addEventListener('resize', this.handleResize.bind(this));
    }
    
  2. Remove Events:

    • Use componentWillUnmount to remove events when the component is unmounted.
    componentWillUnmount() {
      window.removeEventListener('resize', this.handleResize);
    }
    
  3. Minimize Timers:

    • Ensure timers (setTimeout, setInterval) are cleared when no longer needed.
    • Example:
      componentDidMount() {
        this.timer = setInterval(() => {
          console.log('Timer running');
        }, 1000);
      }
      
      componentWillUnmount() {
        clearInterval(this.timer);
      }
      
  4. Audit Event and Timer Usage:

    • Regularly review your application for unnecessary events or timers.
    • Use tools like Chrome DevTools to monitor memory usage.

React Lifecycle Methods Overview

  • componentDidMount: Used for adding event listeners or starting timers.
  • componentWillUnmount: Used for cleanup like removing event listeners and clearing timers.

Real-World Scenario: Handling Window Resize

Example code to handle resize events effectively:

class ResizableComponent extends React.Component {
  handleResize = () => {
    console.log('Window resized!');
  };

  componentDidMount() {
    window.addEventListener('resize', this.handleResize);
  }

  componentWillUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }

  render() {
    return <div>Resizable Component</div>;
  }
}

Key Takeaways

  • Avoid memory leaks by removing unnecessary event listeners and timers.
  • Use React lifecycle methods effectively to manage events and resources.
  • Minimalist event and timer usage not only prevents memory leaks but also improves app performance.

By following these practices, you'll maintain a cleaner, more efficient React application that scales well.

2024

In modern React development, particularly with the advent of React 18, managing side effects like event listeners has evolved to enhance performance and prevent memory leaks. The traditional class component lifecycle methods, such as componentDidMount and componentWillUnmount, have largely been supplanted by functional components utilizing hooks.

Using the useEffect Hook for Event Listeners

The useEffect hook is the standard approach for handling side effects, including adding and cleaning up event listeners in functional components. Here's how you can implement it:

import { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    const handleResize = () => {
      // Handle resize event
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return (
    <div>
      {/* Component content */}
    </div>
  );
}

In this example, handleResize is defined within the useEffect hook to ensure it doesn't change between renders. The cleanup function, returned by useEffect, removes the event listener when the component unmounts, preventing potential memory leaks.

Introducing the useEvent Hook

React 18 introduces the useEvent hook, designed to simplify event handling by providing a stable reference to event handlers without causing unnecessary re-renders. This hook is particularly useful for scenarios where the event handler doesn't depend on the component's state or props.

import { useEvent } from 'react';

function MyComponent() {
  const handleResize = useEvent(() => {
    // Handle resize event
  });

  useEffect(() => {
    window.addEventListener('resize', handleResize);
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [handleResize]);

  return (
    <div>
      {/* Component content */}
    </div>
  );
}

By using useEvent, the handleResize function maintains a consistent reference, ensuring that the useEffect hook doesn't need to re-run unnecessarily. This approach enhances performance and maintains cleaner code.

Best Practices

  • Minimal Use of Global Event Listeners: Whenever possible, prefer component-specific event handling to reduce the risk of memory leaks.

  • Thorough Cleanup: Always ensure that any event listeners or subscriptions are properly cleaned up when the component unmounts.

  • Stable References: Utilize hooks like useEvent to maintain stable references to event handlers, preventing unintended re-renders and potential memory leaks.

By adopting these modern practices, you can effectively manage event listeners in React applications, leading to more efficient and maintainable codebases.

Video Transcript

00:00Welcome to a brand new section
00:02where we cross into the world of the server
00:05as we prepare our code to be isomorphic JavaScript,
00:09which basically means that our code will be able
00:12to work on the client and the server.
00:13But we're gonna start with patching
00:14and preparing our code for the server.
00:17The first step that we're gonna have
00:18to do is set up our server
00:19and get Webpac to know how to interact with Express.
00:23Express is the server side library,
00:25the common server side library that is used on Node
00:29and is also used by Webpac.
00:31So we're gonna take a look at how to set it
00:32and configure it up as we also explore templating systems in
00:36our case EJS,
00:38and we'll look at how to server side render our application
00:41and learn a bit about how modules work in Node.
00:45So with that said, our goal will be to patch up
00:48and get our JavaScript to work on the server.
00:51It's not gonna be completed
00:52'cause we're gonna complete in the next section
00:54as we fix things up for the client side as well
00:57and get ready for production.
00:58But with that said, let's take a look at our first lecture
01:00in this section where we're gonna be building out an express
01:04server that's gonna be used from now on for our development.
01:07We're gonna use Node, we're gonna use Express Js
01:10and we're gonna use Webpac as one of the tools
01:13to build up our server.
01:15So let's jump right into it
01:16and let's see how we configure up and set up our server.
01:21Before we could take control over the process of
01:26building on the Server React application.
01:28We first have to actually stop using React as our server,
01:32but as we do need it for our development purposes,
01:35it would really help us if we could use it
01:38whenever we're in development
01:40and not use it whenever we're not.
01:42But before we do that, we're really gonna have to go ahead
01:44and create a version just so you know how
01:47to set up a server on Node.
01:49So to do that, let me just go ahead
01:51and break out of our current server and I'm gonna go ahead
01:54and use one of the most popular libraries
01:56that are used out there to build out your server.
02:00Now, although Node itself built in has server cap
02:03capabilities, there is a library which is
02:06called Express.
02:10Now, express itself is literally a library that
02:13that makes it easier for you to integrate
02:16and work with with uh, your server.
02:19So it's, it is just a mediator
02:21and it's a mediator that Webpac uses as well.
02:24So that's it. Let's go ahead
02:25and take a look at how do we actually set up
02:27and create a server.
02:29So to do that I'm gonna go into my source
02:31and I'm just gonna add a new file
02:32and I'm gonna call it server js and let me just go ahead
02:36and save it and I'm gonna save it into our source there.
02:39And let's go ahead and, and we're not gonna use
02:43complete E ES six now
02:44because currently in the current version of NPM,
02:48which currently right now when I'm on, I am on uh,
02:52not NPM Atari node.
02:53I'm currently on version 6.3 plus. Okay.
02:56Now in this current version, there is quite a lot
02:58Of new features that were added in
03:00that add support for ES six.
03:02I don't want to use a transcriber,
03:05although there are resources
03:06and I'll leave that in the links of this chapter of
03:08how do you actually turn your server to, to work in E ES six
03:12and then work it down to be node compatible.
03:16But we're not gonna do that ourselves
03:17because we really want our server
03:19to just be natively whatever Node wants it to be.
03:22And there's a lot of logic to that and that is
03:24because Node optimizes its code
03:26based on what it actually is.
03:28So on a logical point of view, it would make sense
03:31to stay at whatever code you're working with to work
03:33with whatever is natively supported inside
03:36of UM, node currently.
03:38So with that said, let me just go ahead
03:39and let me show you the process.
03:40So again, I always,
03:43whenever I'm loading something up, I'm gonna use a constant
03:46that is supported in the current version
03:49of Node if it's not in the earlier
03:50version that you're working with.
03:51And make sure that you use a VAR instead.
03:54And I'm gonna go ahead and require express.
03:56I'm not gonna import because we're not using transcribing.
03:59We're gonna use the standard of Node,
04:01which is the Create JS standard.
04:04Okay? So with that said, I've loaded up Express
04:08and the next thing that I need to do is I'm gonna go ahead
04:10and I'm gonna set a constant
04:11and I'm gonna set my application to be expressed,
04:15which basically is gonna be my, my Express application
04:19that will run our server.
04:20So I'm basically starting it up, I'm starting express Up.
04:24What I want to do next is I want to take this application
04:26and configure, and this is by the way,
04:27where all the configurations that we want to put
04:29for our server happen within this app.
04:32Now when this app is created by default,
04:35it doesn't really do anything.
04:36And then we have to tell it, Hey, what are you going
04:39to do for one?
04:40One of the methods that we can use is the use method.
04:43And the use method enables us to do a lot
04:45of things among them.
04:47We could call the express method of static
04:51and send into it a parameter that tells it
04:53what is the static folder that will be used for our site.
04:57In our case, our public folder is gonna be public.
04:59Now notice that I'm not using here any dots or
05:03or dots to go back one folder and so on and so forth.
05:06The reason is, is because by default express is gonna go
05:10to the root directory of our project, our server itself,
05:13and start from there.
05:14So if I type public,
05:15it's gonna go directly into our public directory.
05:18And all generally speaking, I encourage you
05:21to always work this way.
05:22Don't use paths, it just gets confusing.
05:25Although there's ways to work in other ways,
05:27I'm not gonna get into those.
05:28Now what I've done here is basically I just declared
05:31that take this public folder that's here
05:34and serve that up or use that.
05:36So if anyone is going on our site, it will check
05:39to see if those files exist.
05:40And now because one of those files is an index at HTML,
05:43then our index HTML should render
05:46whenever we go to our root of our directory.
05:49Now there's one last thing that we have to do
05:51before our server could actually run,
05:53and that is to set up a listening to our server
05:55because if I run our
05:56Server just now like this, it's gonna start
05:59and end our process immediately.
06:01But what I wanna do is I want to tell my application
06:03to have a listener to a certain ip.
06:06Now, in a real world scenario, our port
06:08that we would put here would be a real server port such
06:11as 80, but in our case we're gonna put a production port,
06:14which is gonna be 3000 here.
06:16And I'm just gonna create an arrow function,
06:18although I could have put here really any, uh,
06:20I could put here just, uh, anonymous function
06:22as well or any method.
06:23And I'm just gonna go ahead
06:24and set here a small little console log so we could see
06:27that our server is running.
06:28So I'll just write here, our server is running on
06:33Port 3000 and I'm just gonna go ahead and save this.
06:37And literally that's all I had to do to create a very,
06:41very basic server.
06:42And if I go ahead into Terminal and I'll just go ahead
06:45and call Node, that is the command I need to use this time.
06:48I'm not using NPM for this
06:51and I'm gonna approach the directory of my source
06:54and I'm gonna ask for the server itself.
06:57And then once I hit it, it's gonna start up my server
06:59and it's gonna run on Port 3000.
07:01Now the big difference here is that we didn't go
07:03through the compiling process of Webpack anymore.
07:06We just went directly to our server to run it.
07:09If I go ahead into my browser
07:11and click your on refresh, we'll see that now I'm getting
07:13that HTML, our HTML,
07:15which technically right now has no content inside of it,
07:18but I could update it to have here.
07:20Hello World.
07:22And if I go back into my browser
07:25and click your on refresh, I should get
07:27that Hello world in my browser.
07:30But I just want to wrap things up here.
07:32We created our server
07:34and part of this process of the creation of the server was
07:37'cause we wanna work natively with the native code inside
07:40of Node when I'm working in Node
07:41because Node is optimized to whatever code is in there.
07:44So although you have the possibility of working with
07:49other technologies overall, generally speaking,
07:52I prefer running it without pre rendering everything.
07:55'cause we, what would happen is,
07:57and I'm not gonna even get into it, I'll,
07:58I'll leave you files, uh, um, links to read up on
08:01that option of rendering everything out in packaging all
08:04of your server and the files that it uses.
08:07But in my case, I don't really want to do it.
08:08Although we do wanna solve the scenario of actually when we
08:12try to use React because our next step is to try
08:15to get our server to render our elements with React.
08:19And really our next step is gonna be to delete our HTML,
08:21which we'll start looking into in the next lecture.
08:26In this lecture we set up our server ourselves using
08:29express Js.
08:30In the next lecture we'll continue down the path
08:33by setting up a template system so we could inject into it.
08:38React already on the server. I.

Ready to Level Up Your Skills?

Join thousands of learners on 02GEEK and start your journey to becoming a coding expert today!

Enroll Now for Free!