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

Enhancing performance with ES6 const

Enhancing Performance with ES6 const

In this lecture, we focus on using the ES6 const declaration to improve memory management and enforce immutability in React applications. Understanding and applying const effectively is key to writing efficient and scalable code.


Key Concepts Discussed

  1. What is const?

    • A declaration in ES6 used to create variables that cannot be reassigned.
    • Ideal for constants and values that should remain immutable throughout runtime.
  2. Why Use const?

    • Memory Optimization: Values declared with const cannot be reallocated, reducing memory overhead.
    • Code Clarity: Indicates that a variable’s value will not change, aiding readability and maintainability.
    • Performance Preparation: While Babel transpiles const to var for compatibility, using const future-proofs the code for ES6-compatible environments.
  3. The Best Practices:

    • Use const as the default declaration.
    • Opt for let only when a variable needs to be reassigned.
    • Avoid var entirely in modern JavaScript development.

Hands-on Steps

  1. Using const in JavaScript:

    const MAX_USERS = 100;
    const API_URL = "https://api.example.com";
    const userData = { id: 1, name: "John Doe" };
    
  2. Immutability and const:

    • While the reference of a const variable cannot change, the contents of objects and arrays declared with const can still be modified.
    const user = { name: "Alice" };
    user.name = "Bob"; // This works.
    
  3. Babel Transpilation:

    • When transpiling with Babel 6, const is converted into var for ES5 compatibility.
    • Example:
      // Input
      const x = 10;
      
      // Transpiled Output
      var x = 10;
      
  4. Performance Gains:

    • Reduces unexpected behavior by ensuring immutability where required.
    • Aligns with functional programming principles, often used in React.

2024 Updates & Best Practices

  1. Native ES6 Browsers:

    • In 2024, modern browsers fully support ES6. Use const and let without worrying about compatibility.
  2. Immutable Libraries:

    • Consider using libraries like Immutable.js or Immer alongside const for better state management in React applications.
  3. Tree-Shaking:

    • Modern build tools optimize for const during tree-shaking processes, ensuring unused code is removed efficiently.
  4. Transition from Babel 6:

    • Upgrade to Babel 7+ for better compatibility with modern JavaScript standards.
    • Use @babel/preset-env to target the latest browser capabilities.

Practical Application in React

In React applications:

  • Use const for component-level constants such as configuration values or static data.
  • Ensure that asynchronous operations like API calls are properly handled using async/await or Promises.

Corrected Example:

const API_ENDPOINT = "https://api.example.com/users";

async function fetchUsers(endpoint) {
    try {
        const response = await fetch(endpoint);
        if (!response.ok) {
            throw new Error(`Error: ${response.status}`);
        }
        return await response.json(); // Assuming the API returns a JSON response
    } catch (error) {
        console.error("Failed to fetch users:", error);
        return [];
    }
}

function UserList() {
    const [users, setUsers] = React.useState([]);

    React.useEffect(() => {
        async function loadUsers() {
            const userData = await fetchUsers(API_ENDPOINT);
            setUsers(userData);
        }
        loadUsers();
    }, []);

    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    );
}

By adhering to these practices, your codebase remains efficient, readable, and ready for future browser updates.

Video Transcript

00:00In the last lecture, we set up Webpac to run with Babel
00:04so we could transcribe JavaScript from E ES six to ES five.
00:08In this lecture we're gonna take a look at our first
00:11optimization as we take a look at the process
00:14of this transcribing that is done.
00:16And just as a outline, I'm sure you're familiar
00:19with variables and E ES six,
00:21two new definitions were introduced
00:23to the world Let and Const.
00:26In this lecture we'll take a look at const
00:28and get a basic familiarity with
00:29what it actually does and how it's used.
00:32And by default, by the way, you should try to aim
00:34to use ants all the time and move up based on your need,
00:38but really never using var.
00:40You'll be playing around between a cons
00:42or a let generally speaking.
00:44With that said, let's jump into it
00:46and let's see, cons in action.
00:49Alrighty, so the next thing that we need to do to move on
00:52and get our application actually to work is for me
00:55to let you know what's going on in the background.
00:57So this application, um, is basically a JavaScript
01:02or more accurately a React version
01:04of a few different bootstrap components.
01:08Now, among them it's the jumbotron, it's the button
01:11and it, that process we were creating,
01:15we are creating dynamically CSS by importing the, uh,
01:19SaaS files, which we learned more about how to work
01:22with SaaS and what SaaS is in our, in my React UI title.
01:27But assuming that you don't even know what SaaS is
01:29or you do, because it's not gonna be the main point of this,
01:31uh, title, we wanna make sure
01:34that we could import all those stuff
01:35and convert all the different SaaS files
01:38and CSS files that we're importing dynamically
01:41to turn them into, basically into CSS.
01:45Now, to be able to do that, I'm gonna have
01:46to use a few different libraries
01:48and among them, the first one,
01:50because this whole project is based off of version four,
01:53an alpha version of, uh, bootstrap, I'm gonna go ahead
01:57and I'm gonna install those packages.
01:59So MPM install save to Dev
02:01because by the way, I deliberately am building it out.
02:04So we're dynamically building it up
02:06and once we have the compiled version,
02:07we already don't need Bootstrap anymore.
02:10So only we're using Bootstrap in the creation process
02:13because we're only using the CSS of Bootstrap.
02:16So I'm gonna call it Bootstrap
02:19and I'm going to explicitly ask for an explicit version.
02:22In this case, I want Alpha three.
02:24Now as it's in as boot, oh, not Boots Gap Bootstrap Trap
02:30Boot Trap.
02:35So as it's being installed, I just wanna show you
02:38what is actually being used.
02:39If you take a look at our core file core, uh, SaaS release,
02:43uh, SCSS, you'll see that you
02:46that we're importing from Bootstrap SaaS, a few mix-ins,
02:51normalized print buttons and so on and so forth.
02:54So we're importing quite a few different elements
02:56and as we're importing all these elements dynamically
03:00to be used for our buildup of our CSS,
03:04we we're basically loading up those items,
03:07we're loading up those core items
03:09and we're adding in our own extra items if we need
03:12to add them in.
03:14So to be able to do that, I need to make sure that I first
03:17actually downloaded Bootstrap Alpha three.
03:19Don't worry about the fact that it needs jQuery
03:21'cause we're actually not using the actual library itself.
03:24We're only fetching resources from it.
03:27The next things that I'm going to go ahead
03:29and I, I'm gonna, I'm gonna install a few more packages
03:32that are gonna enable me
03:33to basically dynamically using Webpack to load in CSS.
03:38So the first of them is gonna be CSS loader,
03:40which is gonna do exactly that.
03:43The second of them is gonna be the SaaS loader
03:46and the SaaS loader enables me
03:48to load SaaS files if you use less than look into the
03:51documentation of less.
03:52But in our case we're, for this project, we're using SaaS.
03:55So we're gonna use that loader, which needs then a library
03:58that actually converts SaaS files,
04:00which is called Node SaaS.
04:03Last but not least, we're gonna use another plugin
04:05of Webpack that enables us to bundle up all of our CSS
04:09and SaaS files into one file.
04:12To do that, I'm going to call the extract text web pack,
04:20Uh, plugin.
04:22That was a mouthful. Okay,
04:24so the Extract text web pack plugin is gonna be the plugin
04:27that will be basically the driver
04:28that will create the file for us.
04:30So as it's going ahead
04:32and installing, I'm gonna go into Webpack
04:34and I'm gonna show you the process of this installation.
04:38Alright, so inside of our Webpack config, I'm gonna, first
04:41of all, in my first step I'm gonna go ahead to my loaders
04:44and what I really want to do is I want
04:45to create two more loaders.
04:47So lemme just go ahead and I'm gonna copy this out
04:50and on contrary to previously that we only sent in a loader,
04:53what we really want to do is we want
04:55to create a wrapper loader.
04:57You could say, so first of all, there's one thing
04:58that we'll do if it's a CSS file, there's another,
05:01if it's gonna be SAS or uh, CSS.
05:05So for example, in this case, I'm gonna,
05:07let me just copy this and I'm just gonna copy that
05:10and in this case I'm gonna take it
05:11or for, um, let me just put your version,
05:14if it's a SaaS file,
05:16although in our case our files are only SCSS more on
05:20that in our other titles.
05:22Okay, so these are the file types that we want to test for
05:24and what are the loaders that we want to load up for them?
05:27That is the big question
05:29and really what we're going to be solving right now.
05:32So first of all, for me to be able
05:33to use my extract text plugin, really I want both this
05:37and that to end up in the same CSS file.
05:40So to be able to do that, I first need to create, uh,
05:42a reference to this element
05:44and to create a reference to this element,
05:46I'm gonna go right above before I'm exporting anything
05:49and I'll create a new variable
05:50and I'll call it extract text plugin.
05:54And I'm gonna require,
05:56and this is how we do this, how we load things up in um,
06:00common JS in node.
06:02Generally speaking, I use a require.
06:04And in that require, I'll go ahead
06:06and let me just see if it's loaded up already.
06:08And it sure did. I'm gonna load up extract text web pack
06:11plugin and let me just grab that and paste that right there
06:14because I need access to this plugin.
06:17Once I've created this plugin and I could have
06:20and I could refer to it
06:22and interact with it, I could go ahead here into our loader.
06:25I'm gonna basically extract out using the extract command
06:31our CSS using the CSS loader.
06:33And I'm gonna do the exact same thing.
06:35Let me just copy that. The exact same thing.
06:37I'm gonna do Oso for our SaaS or CSS,
06:40but in this case, not only am I gonna send CSS,
06:43I'm gonna send the CSS loader and the SaaS loader.
06:46So it's gonna basically make sure that it's gonna go
06:48through the C uh, fetch our CSS
06:51and make sure that it's gonna go through the SaaS loader
06:53to make sure that it knows how
06:54to transcribe the information that is there.
06:57So those are the two elements that I had there.
06:59And the last thing that's left for me to do is to call in
07:02and start up this loader.
07:03And to do that I'm gonna go after our modules
07:06and lemme just break a few lines here
07:07so it's not on the bottom of our screen
07:09and I'm gonna call plugins.
07:12And Plugins is literally an array of ADD-on features
07:15that we want to add into Webpack.
07:17And in this case, what I want to do is I want
07:19to call this new oopsie new Extract text plugin.
07:24And I'm gonna call it defining it, the actual CSS,
07:27that it's going to file names that is gonna be called Now,
07:31by the way, that's exactly also inside of our CS HTML,
07:34we're referring to that app that CSS as well.
07:37So literally the process that we've done here is we've,
07:40we got the plugin itself, the text extract plugin,
07:43which is gonna be used to extract the text
07:45and in this case I'm extracting out CSS
07:48and then I'm extracting out in the, if it's a file
07:51that is SaaS or that this item, I'm going ahead
07:54and extracting CSS SaaS, basically compiling it down,
07:57turning it into CSS and extracting that.
08:00And then I am creating it into its own
08:03distinct package file, which is called App css.
08:06Now, as this title is all about performance, uh,
08:09we can't end this, this lecture without a little bit
08:11of something about performance.
08:13So let's talk about one thing that is new to E SES six that
08:16by the way is supported by Node in the later version 6.0
08:20and onwards is that we could use constant, now a constant,
08:23we'll take a deeper look into how they work later on,
08:27but a constant per se, all it really does is make sure
08:31that the content that we're loading in cannot be changed
08:34once we created it.
08:35This is the content that is going to be used
08:37and in our case, anytime really, generally speaking,
08:39you want to use everything as a constant if you can.
08:42And only whenever there's something
08:44that actually is a variable that is going to change,
08:47then you would wanna define it as a VAR
08:49or alet, which we'll talk about later.
08:51Now, what that will do is it's gonna make sure
08:53that the allocated memory that is needed to
08:56to be holded is only gonna be allocated for the item
08:59that is there and it won't need
09:01to allocate more memory than that.
09:03With that said, because all
09:04of our client stuff is actually gonna be rendered out into
09:08ES five, all these cons
09:09that we're using throughout is actually then transcribe down
09:14actually into just the var.
09:16But once we get to a point in time
09:18where we're actually running things on the browser oso
09:21with ES six, the usage of cons will improve our memory.
09:24So by coding this, we're preparing ourselves for the future
09:27of ES six in browsers as well.
09:30So with that said, if I go ahead
09:32and save this, if I don't have any errors in my application,
09:35lemme just go ahead and test out
09:36and see if this time around it's actually going to,
09:39let me just call it NPM start.
09:43And if I call my NPM start
09:44and my server starts, if I didn't have your error,
09:46let me just double check and triple check to see
09:49what is the error itself.
09:50And I can see that my error is, um, right about here inside
09:54of our SaaS, uh, area here.
09:57So let's just check to see what's wrong there.
10:00So in my webpack config, our error is right about here.
10:05So first of all, we have your a loader extract this plug,
10:08and that all looks good.
10:09That looks good as well.
10:11And maybe that we have her in extra comma,
10:17I don't think so, but let's double check.
10:20This is the loader loader extract.
10:23That looks all, looks good to me.
10:25Okay, so let me just save this and let's go ahead
10:28and let's also remove any usage
10:30of commas whenever they're not needed.
10:31So also the loaders had an extra comma and let's go ahead
10:35and clear things up and give it another run.
10:38And hopefully this, this time around our server will run,
10:40but it did not run.
10:42Let's see if it's taking us
10:43to exact same place if it's giving us
10:44something uh, expected.
10:46Okay. Oh yeah, there you go.
10:48I've typed your loader twice by mistake.
10:50So that's it for not reading doc, reading the actual error.
10:54You can see that here. It's telling me that I exactly
10:57where the error is.
10:58So let's go ahead and try it one more time.
11:00And this time around, hopefully our server will start.
11:02We won't have an error. And if that's,
11:04so once we go into our browser, let's give it a refresh
11:07to make sure that it connects to our server.
11:09We should get our actual real final product outcome
11:14that we had in our Building React user interfaces title.
11:19So with that said, now that we got all
11:21of our configurations done, it's time for us
11:23to dive much deeper into performance related tasks.
11:28In this lecture, we completed our configuration
11:31of our project because now we could start typing in E ES six
11:35and have it transcribed just as we need it to be.
11:39And we're done with this section.
11:40In the next section, we're gonna move into performance
11:43enhancements in e ES six in general, as they relate
11:47to React.

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!