skull

Robert Tamayo

R
B
blog
skull

Native JS Compared to React for Only Rendering HTML

Yesterday, I wrote about using native Javascript to handle tasks which are normally taken care of by a framework such as React. The important thing to keep in mind is that I'm not saying I invented anything here. I'm literally doing the opposite - I'm using native Javascript, so there is quite literally no invention. I'm not creating a framework - I'm using regular js to see how far it can get before a framework seems necessary.

For the purpose of rendering HTML based on data, I don't think anyone would argue that native Javascript holds its own. Both the react code and the native js code shown later have 16 lines, but the native js code is still technically far fewer lines of code once the React codebase itself is considered. There is an assumption that the actual render function is called elsewhere in both cases. Also, keep in mind the Video function must be defined globally or included in the scope via import, just as the React Video component would need to be as well.

Here is a simple sample taken directly from the React website.

function VideoList({ videos, emptyHeading }) {
    const count = videos.length;
    let heading = emptyHeading;
    if (count > 0) {
        const noun = count > 1 ? 'Videos' : 'Video';
        heading = count + ' ' + noun;
    }
    return (
        <section>
        <h2>{heading}</h2>
        {videos.map(video =>
            <Video key={video.id} video={video} />
        )}
        </section>
    );
}

Here is the above templating achieved using only native js. 

function VideoList({ videos, emptyHeading }) {
    const count = videos.length;
    let heading = emptyHeading;
    if (count > 0) {
        const noun = count > 1 ? 'Videos' : 'Video';
        heading = count + ' ' + noun;
    }
    return `
        <section>
            <h2>${heading}</h2>
            ${videos.map(video =>
                Video(video)
            ).join('')}
        </section>
    `;
}

Native js does a great job of doing all of the same things. There is no need to consider the rules of a framework when writing the code; only the rules of Javascript itself apply here. That alone is a huge benefit, in my opinion.

I know React does a lot more under the hood to keep things from re-rendering all the time, but I'll get there when I get there. Right now, I'm thinking that React itself might have created that issue by insisting too much on sticking to a design paradigm. But then again, I might encounter that problem tomorrow when I implement tabs to switch between content. I assume things will get even trickier when I add event handling.

Comments:
Leave a Comment
Submit