Alternatives to React: Preact
Published: 2022-08-29 22:29:53


by [Amazing Enyichi Agu](https://blog.openreplay.com/authors/amazing-enyichi-agu)

> **Alternatives to React** is a series of articles looking at different JavaScript front-end frameworks. All the examined frameworks are like React in syntax and operation, but they may have benefits React doesn't provide. The first two articles in the series were [Alternatives to React: Solid JS](https://blog.openreplay.com/alternatives-to-react-solid-js) and [Alternatives to React: Inferno JS](https://blog.openreplay.com/alternatives-to-react-inferno-js), with more to come.

## Introduction

Preact is a front-end library for building User Interfaces (UI) just like [React](https://reactjs.org). According to the [official documentation website](https://preactjs.com), Preact is a "Fast 3kb alternative to React with the same Modern API".

![1 Preact's Homepage](https://blog.openreplay.com/static/a296c095e27087e55cf2e8e1759667fd/59b3f/image01.png)

A quick look at the features of Preact shows that it is almost the same as React, considering that it uses a virtual DOM, context, hooks, etc.

In this article, we will deeply dive into the world of Preact. We would learn why the library was created, how it works, and how it compares to React. We would also discuss if we should ever use Preact. 

Before proceeding, note that this article is not a tutorial on starting Preact. Preact provides an [excellent tutorial](https://preactjs.com/tutorial/) on their website. Instead, this article compares React and Preact to aid you in making informed decisions on the framework to choose for a project.

On that note, let us begin.

## Origin of Preact

[Jason Miller](https://github.com/developit), a Canadian software developer, is the author of Preact. In a talk titled ["Putting the P in Preact"](https://youtu.be/TQptGQlGXqA), Jason stated that he had built a lot of UI frameworks/templating engines for the web. 

Jason could never build a perfect framework that supported everything he wanted. He kept having issues relating to the Document Object Model (DOM). He then discovered that JSX and React satisfied his need and what he wanted in a framework.

When Jason found this solution, his next step was learning React. To learn React, he needed to create a project that worked how React worked. He learned better when he was building.

Preact started as a [Codepen](https://codepen.io/) file that rendered hundreds of DOM elements like React would. Jason kept optimizing the program and adding features. One day he ran speed tests on desktop and mobile for his program. The results he got were very good, and they were way faster than React. The speed was very close to that of plain JavaScript.

According to the talk ["Putting the P in Preact"](https://youtu.be/TQptGQlGXqA), Jason continued with the project. He made it into a library for developers who couldn't afford the high cost of performance in React. Preact had almost the same features as React, just lighter and faster. The first release of the library on Github [(v2.0.0)](https://github.com/preactjs/preact/commit/1267babd0d259ce257b607da246a63d3713bdc7f) is dated back to November 13th, 2015.

Since then, the Preact community has been growing with users, contributors, and maintainers.

## How does Preact work?

Preact works very similarly to React, but it still has its separate implementation of many of React's features. In this section of the article, we will look at Preact's core functionality, breaking it down into three categories. These categories are:

- Virtual DOM
- No Build Tools
- Embeddability

### Virtual DOM

The **Document Object Model (DOM)** represents the hierarchy of elements in any HTML document. Every element on a web page can also be located on the DOM. On the other hand, the virtual DOM is a generated clone of the real DOM. 

Most frameworks use virtual DOMs because the real DOM is slower to render when updated with JavaScript. This is a big issue for Dynamic applications because they need to update their elements constantly.

According to [Codecademy](https://www.codecademy.com/article/react-virtual-dom), Virtual DOM-enabled rendering in React goes through the following phases:

1. The whole of the Virtual DOM gets updated.
2. The Virtual DOM gets compared to what it looked like before the update. React figures out the changed elements (This process is also known as [Diffing](https://www.geeksforgeeks.org/explain-dom-diffing/?ref=rp)).
3. React updates only the changed elements on the real DOM (This process is also known as [reconciliation](https://www.geeksforgeeks.org/reactjs-reconciliation/?ref=gcse)).
4. User sees updated change on the page.

Preact doesn't implement its virtual DOM like React. On the documentation website, it states that:

> "Preact provides the thinnest possible Virtual DOM abstraction on top of the DOM. It builds on stable platform features, registers real event handlers, and plays nicely with other libraries." ([Source: Preact](https://preactjs.com/))

In simple terms, this means that Preact's virtual DOM only handles processes the real DOM would find time-consuming. Preact efficiently uses a virtual DOM, unlike React, which gives every task to the virtual DOM. 

Preact also doesn't use [Synthetic events](https://reactjs.org/docs/events.html), which are an abstraction of a normal [DOM Event Object](https://developer.mozilla.org/en-US/docs/Web/API/Event). Instead, Preact uses the real event handlers of elements and their corresponding event objects. This makes Preact's virtual DOM smaller and more performant.

### No Build Tools

Build tools are libraries that perform recurring tasks for a developer and save time. These kinds of tasks include [CSS Preprocessing](https://www.freecodecamp.org/news/css-preprocessors/), [code linting](https://www.freecodecamp.org/news/what-is-linting-and-how-can-it-save-you-time/), trans-compiling files, bundling files, compressing images to mention but a few. Some examples of build tools are [Parcel](https://parceljs.org/), [Webpack](https://webpack.js.org/) and [Browserify](https://browserify.org/). React JS, like other front-end frameworks, relies on build tools under the hood to create optimal production output after development.

Even though build tools help during development, they might increase the complexity of projects. The developer might have to deal with configuration files or simply spend time learning how to use a new tool.

Preact is shipped as an already working solution and does not need a build tool to function properly.

A simple Preact App can be built by importing the `preact` library into an HTML page.

```
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Simple Preact App</title>
    </head>
    <body>
        <!-- PREACT APP -->
        <script type="module">
            import { h, Component, render } from 'https://unpkg.com/preact?module';

            // Create your app
            function App() {
                return h('h1', null, 'Hello World!');
            }

            render(App(), document.body);
        </script>
    </body>
</html>
```

(Snippet modified from [Preact Website](https://preactjs.com/guide/v10/getting-started#no-build-tools-route))

From the above illustration, because `App` is a javascript function that returns an `h1` element, the function needs to be called as an argument of the render function. 

With `app` declared as a variable, this works too.

```
<script type="module">
    import { h, Component, render } from 'https://unpkg.com/preact?module';

    // Create your app
    const app = h('h1', null, 'Hello World!');

    render(app, document.body);
</script>
```

However, a build step is required to use JSX for DOM elements in Preact. Preact provides an alternative to JSX called `htm` with similar functionality and syntax but doesn't require a build step. We will look at `htm` later in this article. Preact doesn't need a build tool to get the best out of it.

### Embeddability

HTML has an `iframe` tag that enables a particular website to be displayed (embedded) on another. The importance of embedding websites on other websites is high. Great use of this is to display data that is not originally supported on the host website (videos, games, music, maps, and so on). Embedded Web Apps that have functionality are called Widgets.

Below is a Todo Widget built with Preact.

<iframe src="https://developit.github.io/preact-todomvc/" width="100%" height="400px"></iframe>

Preact was built with ease of embeddability, which is why Preact Applications can fit into any website and load as fast as possible.



## Open Source Session Replay

_[OpenReplay](https://github.com/openreplay/openreplay) is an open-source, session replay suite that lets you see what users do on your web app, helping you troubleshoot issues faster. OpenReplay is self-hosted for full control over your data._

![replayer.png](https://static.openreplay.com/images/banner-blog.png)

_Start enjoying your debugging experience - [start using OpenReplay for free](https://github.com/openreplay/openreplay)._




## How does Preact compare to React?

In this article section, we will compare the two frameworks using some criteria. These criteria are essential when picking a framework/library for a project. They are:

- Syntax
- Size
- Speed
- Popularity

### Syntax

Comparing the syntaxes of Preact and React, below are some differences. 

- **Passing of State and Props to the Render method**: As mentioned earlier, the `render` method of class components can accept props and states. A representation of this is found below. In React, the `render` method does not accept any parameters. 

```javascript
render(props, state) {
    // Return Component
}
```

- **Use of `class` instead of `className` in components**: As we can see below, we can use `class` instead of `ClassName`  in Preact (`className` is also accepted).
```javascript
function Hello(){
    return (
        <h1 class='hello-box'>Hello World!</h1>
    );
}
```

- **Components**: In Preact, developers can create components in three different ways. They are:

  - Using [JSX](https://reactjs.org/docs/introducing-jsx.html). JSX is the most common way to render components in Preact.

```javascript
function JsxComponent(props) {
    return (
        <h1>I am rendered with JSX</h1>
    )
}
```

    - Using [`h` or `createElement`](https://preactjs.com/guide/v8/api-reference/#preacth--preactcreateelement). `CreateElement` and `h` are functions that return virtual DOM elements in Preact. React developers can use `createElement` in Preact as it is modeled after `React.createElement`.

```javascript
import { h } from 'preact';

function HComponent(props) {
    return h('h1', null, 'I an rendered with h')
}
```

    - Using [`htm`](https://preactjs.com/guide/v10/getting-started#alternatives-to-jsx). `htm` is the recommended way of creating components in Preact. This is because using `h` or `createElement` can be tedious. Also, JSX needs to compile to standard JavaScript before it works. `htm` combines the power of `h` and the ease of JSX.

```javascript
import { h, render } from 'preact';

import { htm } from 'htm';

// Initialize htm with Preact 
const html = htm.bind(h);

function HtmComponent(props) {
    return (
        html`<h1>I am rendered with HTM</h1>`
    )
}

```

React developers can only create components in two ways: using JSX and using `React.createElement`. A conclusion to draw here is that there is slightly more flexibility in creating Preact Components.

### Size

As stated on Preact's website, it is a library with a tiny size of 3kb. [Bundlephobia](https://bundlephobia.com/package/preact@10.8.2) reports that Preact's size, minified and gzipped, is 4kb. 

![2 Preact's size on Bundlephobia](https://blog.openreplay.com/static/c03b43dedaf4817301518f74f822c403/b71f8/image02.png)

An npm package named [`package-size`](https://www.npmjs.com/package/package-size) also confirms this.

![3 Preact's size on package-size npm package](https://blog.openreplay.com/static/efe777d077305e28fc7e01ed565f8631/b02fc/image03.png)

A possible reason is that newer updates have increased the source code size. However, Preact has always maintained the under 4kb size by periodically removing deprecated features or dedicating some APIs to separate modules.

It is still impressive for Preact to be that small, considering that using React requires over 40kb of memory. A React Application requires [`react`](https://bundlephobia.com/package/react@18.2.0) and [`react-dom`](https://bundlephobia.com/package/react-dom@18.2.0) with sizes of 2.5kb and 42kb respectively (Minified + Gzipped).

### Speed

Speed is a huge factor to consider when choosing a framework. We would compare Preact to React using [Stefan Krause's Javascript frameworks benchmark](https://krausest.github.io/js-framework-benchmark/2022/table_chrome_103.0.5060.53_osx.html). The experiment tests frameworks on three categories. These categories are: 

- Duration: The duration category determines the number of milliseconds it takes javascript frameworks to render or update changes on a page. The tasks assigned to the frameworks here include creating 1,000 rows of a table, updating all 1,000 rows of the table, appending 1,000 rows to a table of 10,000 rows, and so on. While React appeared to be fast in the latest [experiment](https://krausest.github.io/js-framework-benchmark/2022/table_chrome_103.0.5060.53_osx.html#772) published before this article,  Preact beat React on average in this category. This means that, on average, Preact updates the DOM faster.

- Startup metrics: These are taken with [Lighthouse](https://developer.chrome.com/docs/lighthouse/overview/) and simulate the website on a mobile device. It runs tests on how the frameworks properly utilize the CPU. This category also measures the build sizes of assets of a framework in production. Both frameworks performed well here, but Preact still beat React.

- Memory Allocation: This measures the amount of memory a framework uses while in session on a browser. This memory is measured in Megabytes (MB). In this category, things like memory usage after page load, memory usage after adding 1000 rows, memory usage after creating 1000 rows five times, and so on are measured. On average, Preact performed slightly better than React utilizing lower memory in all scenarios. An article that goes in-depth on the interpretation of the benchmark can be found here on [this blog post](https://dev.to/ryansolid/making-sense-of-the-js-framework-benchmark-25hl).

### Popularity

One final factor we are going to consider is popularity. How prevalent are the frameworks compared to each other? The popularity determines the amount of help a developer would receive when they get stuck on a project.

In the last [State of JS survey](https://2021.stateofjs.com/en-US/) conducted before this article, Preact came sixth (80%) in awareness as a front-end framework. Most respondents had heard of the framework, even though React beat Preact.

![4 Awareness of Preact](https://blog.openreplay.com/static/2851ce4e0ea5a31a75a5600cdf41c54a/abddd/image04.png)

In usage, it turned out that only 14% of the respondents use Preact. React also beat Preact in this category.

![5 Usage of Preact](https://blog.openreplay.com/static/ff88d7487a4c5627d74162c97a147761/0be4b/image05.png)

Preact happened to be falling in interest and satisfaction every year from the charts.

![6 Interest in Preact](https://blog.openreplay.com/static/936ed4384532ce064757deb9138213d5/32b8b/image06.png)

![7 Satisfaction of Preact](https://blog.openreplay.com/static/80abff9650909d38d198db445ea39dd7/68d7c/image07.png)

A curve like this isn't a good one for a framework, but the interest and satisfaction of React are dropping too. Still, [millions of websites](https://trends.builtwith.com/javascript/React) are powered by React today. So I don't think this is something to worry about too much.

The following holds for both frameworks in terms of NPM Weekly downloads and GitHub stars.

- Preact
    - [Github Stars](https://github.com/preactjs/preact): 32K
    - [NPM Downloads](https://www.npmjs.com/package/preact): 1.4M
- React
    - [Github Stars](https://github.com/facebook/react): 191K
    - [NPM Downloads](https://www.npmjs.com/package/react): 16.2M

## Conclusion

In this article, we have looked at Preact as an alternative to React. We started by finding out how the framework came to be, and then we looked at the features of the framework. We also compared the framework to React in some categories.

The small size and speed Preact has is truly an advantage over the relatively giant-sized React and React DOM. This advantage is what has attracted [Dev.to](https://dev.to), [Etsy](https://etsy.com), [Smashing Magazine](https://next.smashingmagazine.com/), [Uber](https://uber.com/) and [many other popular organizations](https://preactjs.com/about/we-are-using) to add Preact to their stack.

You should use Preact if you want to make a new Single Page Application more lightweight or if you want to build a dynamic widget for a webpage. If the application already exists and you would still like to move to Preact, Preact provides a feature called [`preact-compat`](https://preactjs.com/guide/v10/switching-to-preact/) to do so.

## Resources
- [Getting Started with Preact](https://preactjs.com/guide/v10/getting-started)
- [Preact Components](https://preactjs.com/guide/v10/components)
- [Difference between Preact and React](https://preactjs.com/guide/v10/differences-to-react)


> A TIP FROM THE EDITOR: You may be interested in reading [An introduction to Fresh](https://blog.openreplay.com/an-introduction-to-fresh), a framework that uses Preact for rendering and templating.



[![newsletter](https://blog.openreplay.com/static/e6b18eda7a327511296a2f27692f9c70/e9957/newsletter.png)](https://newsletter.openreplay.com/)