paint-brush
React Developers Love Preact, Here's Whyby@sojinsamuel
2,889 reads
2,889 reads

React Developers Love Preact, Here's Why

by Sojin SamuelJune 30th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

React and ReactDOM have a combined size of 130KB when minified (or 42KB when Gzipped) If you're looking for a lighter option, Preact is a great alternative. Preact weighs in at around 10KB when it's been minimized (compressed to its smallest size), and only 4KB when gzipped.
featured image - React Developers Love Preact, Here's Why
Sojin Samuel HackerNoon profile picture

Hey there 👋


As a fellow React developer, I wanted to share some insights with you about a cool library called Preact. The main aim of this article is to give you a friendly introduction to Preact, which you may find useful if you're already familiar with React.


So, let's talk about size. In terms of file size, React itself weighs around 6KB, while ReactDOM adds approximately 130KB to that. When combined, they amount to roughly 136KB of code that the browser needs to process. Now, keep in mind that these numbers refer to the minified code that the browser reads.


You might come across people mentioning the size after compression using GZip. In the case of React and ReactDOM, that compressed size would be around 42KB.

Gzip vs. Minification

Gzip is actually a compression algorithm that works by compressing JavaScript code prior to sending it from the server to the browser. Nevertheless, it's important to keep in mind that when the Gzipped file is being transferred (let's say 45KB are sent from the server to the browser), the browser subsequently needs to decompress the Gzipped version.


As a result, the browser isn't just parsing and executing 42KB of code but rather around 130KB of minified JavaScript code.


To put it simply, when you have a JavaScript file with React + ReactDOM that is compressed (or minified), it takes up around 130KB. But when a user visits your website, the server compresses it further using Gzip, reducing its size to 42KB. So, the browser only needs to download this smaller 42KB file.


Once the file is downloaded, the browser then uncompresses it, and the file returns to its original size of 130KB. This uncompressed code is what the browser parses, compiles, and executes to make your website work.

Mass Entry of Preact

React and react-dom have a combined size of 130KB when minified (or 42KB when Gzipped), but if you're looking for a lighter option, Preact is a great alternative.

Source: BundlePhobia.com


Preact weighs in at around 10KB when it's been minimized (compressed to its smallest size), and only 4KB when gzipped (compressed even further).

Source: BundlePhobia.com


Now, there are instances where Preact alone might not suffice, and that's when you might need to bring in preact-compat. However, be aware that using preact-compat adds an additional 14KB to your bundle size (10KB uncompressed) or 5KB when gzipped.


The combined size of preact and preact-compat is around 24KB (9KB after compression). I'll provide a detailed explanation of the role of preact-compat in a later section of this article.

When Should you use Preact, then?

I totally get that you might be curious about whether the difference makes a significant impact on your website's performance.

Well, the answer is a bit tricky. It actually depends on various factors.


Based on your target audience and the type of device they use. It also depends on how much JavaScript you're currently including. If you happen to be sending out a whopping 2MB of uncompressed JavaScript (which is not ideal), reducing it by 100KB may not make a significant impact.


But the most crucial thing to consider is your target audience. I've had the opportunity to work with various companies as a freelancer, helping them with Web Performance. It's fascinating to see how, based on their specific target markets, they can sometimes manage to deliver more JavaScript to the browser without any issues.


On the flip side, Hackernoon has readers from all around the globe, which is why they always prioritize performance to ensure accessibility for as many people as possible.


To sum it up, if your target audience primarily uses laptops or the latest top-of-the-line smartphones, you likely don't need to be concerned about the size difference between React and Preact.


When making such decisions, it's crucial to assess the performance of your website both before and after implementing any changes, in order to gauge the impact it has.


Additionally, it's worth considering that not all libraries and frameworks are compatible with Preact, so it would be a good idea to look into that aspect as well.

My Personal Suggestion

If you're diving into the world of website building for the first time, I would highly recommend sticking with React. It's a great choice because it offers a simpler way to tackle any bugs that may come your way. Plus, having some experience with Preact can be a nice addition to bring up during an interview.

Can Preact fully replace React?

According to the Preact documentation, Preact is not meant to be a direct substitute for React. While there are differences between the two, many of these differences are minor and can be eliminated by using preact-compat. This tool acts as a thin layer over Preact, striving to achieve complete compatibility with React.


In the following sections, I'll demonstrate some typical scenarios where Preact is used. One of these cases involves utilizing preact-compat, while the other doesn't require it.

Building with Preact

If you're considering using Preact, there are two primary scenarios to explore:


  1. Starting a brand new app using Preact: If you're starting a project from scratch and want to leverage the power of Preact, this use case is perfect for you.

  2. Migrating an existing app from React to Preact: If you already have an app built with React and want to take advantage of Preact's benefits, this use case will guide you through the migration process.


In the upcoming section, let’s focus on the first use case: creating an app from scratch using Preact.


Let's get started and discover the possibilities!

Installation

To begin a new Preact project, I recommend using the preact-cli tool. First, make sure you have it installed globally by running the following command:

npm install -g preact-cli

Once the installation is complete, navigate to a folder of your choice in the command line and run the following command to create a new project:

preact create default my-project

Feel free to replace my-project with the desired name for your project. This command will utilize the default template.

However, if you'd like to explore other templates, you can see a list of them by running:

preact list

Understanding JSX and h()

When you open the file src/components/app.js, you'll see that the code might seem familiar to you. However, there are just a couple of distinctions to be aware of.

import { h } from 'preact';
import { Router } from 'preact-router'
  1. Preact-router is a great alternative to react-router if you prefer a more minimal approach. If you find that it doesn't meet all your needs, you can combine preact-router with preact/compat. I will discuss preact/compat in the upcoming section.

  2. In this code, we import an h function from preact, although it doesn't seem to be used anywhere in this file. The h() function plays a role in converting your JSX code into Preact elements, similar to how you needed to import React for JSX to work in React. Essentially, h() serves a purpose similar to React.createElement.


Note: In modern Preact projects, the h() method is no longer necessary and may be removed from the boilerplate in the future.


Here's an example of a complete Preact component that gets rendered to the DOM

import { h, render } from "preact";

const App = () => (
  <div>
    <h1>Preact App</h1>
  </div>
);

render(<App />, document.querySelector("#react-root"));

As you can see, the render method is exported from the same preact package as well.


You can also use the Preact's h function instead of the default JSX syntax like so:

import {h, render} from "preact";

function App() {
    return h('p', null, 'Preact App');
}

render(h(App), document.querySelector("#react-root"));

And this will render into the DOM as:

<p>Preact App</p>

I admit it’s a bit wordy. But it’s good to know the React.createElement we can also achieve something similar with Preact’s h function.

Migrating an existing app from React to Preact

If you're in this situation, chances are you're using some React features that aren't available in Preact.


That's where preact-compat comes in. It's designed to be a seamless replacement for React.


For bigger projects, you can instruct webpack to use preact-compat instead of React.

So, whenever webpack comes across these imports:

import React, {useState, useEffect} from "react";
import {createRoot} from "react-dom/client";

Instead of bringing in those objects and functions from the react package, we'll import them from the preact-compat package instead.


In order to get this up and running smoothly, you'll have to install preact-compat and make some configurations in webpack to switch out these packages. This can be achieved by updating the resolve option.

npm install preact-compat

And inside your webpack.config.js:

{
    // ...
    resolve: {
        alias: {
            'react': 'preact-compat',
            'react-dom': 'preact-compat',
        }
    }
    // ...
}

For more detailed information, you can refer to the official documentation.

Are you going to use Preact?

In this article, we explored how you can utilize preact and preact-compat to shrink the size of your React applications, especially when performance plays a crucial role in your business and target market.


If you're curious, I'm also considering writing about React lazy. Just give me a shout-out if that interests you. Feel free to share your thoughts and concerns in the comments section. Until then, enjoy coding and have a great time!


Also published here.