Yomi Eluwande JavaScript developer. Wannabe designer and Chief Procrastinator at Selar.co and worklogs.co.

Introduction to Preact : A smaller, faster React alternative

6 min read 1888

Preact is a JavaScript library that describes itself as a fast 3kB alternative to React with the same ES6 API. As a frequent user of React, I’d always wanted to try out Preact and see what it offers, and the differences between Preact and React. In this article, I’ll do an introduction to Preact, its key concepts and differences between Preact and React.

I’ll also demonstrate how Preact works with external APIs by building a Preact app that shows the most recent debut shots from Dribbble.

Introduction to Preact

As mentioned above, Preact is a 3kb alternative to React developed by Jason Miller and a bunch of contributors. Preact was developed with the goal of building a JavaScript framework that’s small in size and yet offered the same API and features that React ships with.

With a total size of 3kb, this means you don’t have to worry about your JavaScript library/framework taking up a major chunk of your app’s total JavaScript size.

Preact is fast, and not just because of its size. It’s one of the fastest Virtual DOM libraries out there, thanks to a simple and predictable diff implementation.

Preact aims to deliver on a few key goals:

  • Performance: Render quickly & efficiently
  • Size: Small size, lightweight
  • Efficiency: Effective memory usage
  • Understandability: Understanding the codebase should take no more than a few hours
  • Compatibility: Preact aims to be largely compatible with the React API. preact-compat attempts to achieve as much compatibility with React as possible. More on preact-compat later.

Preact performs nicely with browsers (supports all browsers) although it may require some polyfills for IE7 and IE8. Preact has also seen a large adoption by the community with a plethora of plugins and companies are now beginning to switch to the JavaScript library.

Preact is now being used by companies like Lyft, Housing.com and m.uber.com. Uber’s engineering team recently wrote an article that highlighted how Preact was used to build the mobile version of Uber which in turn led to a better performance largely due to its very minimal size.

What makes Preact different from React?

That’s the question a lot of React developers would be asking as Preact is considered. React is already a decent JavaScript library which weighs in at ~45kb. So why would you consider building apps with Preact?

Preact itself is not intended to be a reimplementation of React. There are differences. Many of these differences are trivial, or can be completely removed by using preact-compat, which is a thin layer over Preact that attempts to achieve 100% compatibility with React. — Preactjs.com

File Size

Well for starters, there is a huge gulf in file size. Preact’s 3kb against React’s 45kb is a no brainer. The reason Preact does not attempt to include every single feature of React is in order to remain small and focused.

class vs className

When using React, if you wanted to add a class to a div you’d have to do something like this.

# React code
<div className="class-here">Content Here</div>

In Preact, you can just use class for CSS classes. className is still supported, but Preact encourages you to use class .

# Preact code
<div class="class-here">Content Here</div>

render()

In Preact, this.props and this.state are passed to render() for you. What does this mean? Take a look at the code below.

As you can see above, in Preact, we can make the code look cleaner by removing the this and if you even want to go a step further, you can use destructuring. See an example below.

Removal of PropTypes

Not everyone uses PropTypes, so they aren’t part of Preact’s core, hence the removal from Preact. If you’d still like to use PropTypes in your project, you can do so with the help of preact-compat or use them manually.



Using preact-compat for compatibility between Preact and React

Preact has this package called “preact-compat” which works as a compatibility layer between Preact and React. Using preact-compat makes it easy to switch from React to Preact. Switching to Preact can be as easy as installing and aliasing preact-compat in your code.

This lets you continue writing React/ReactDOM code without any changes to your workflow or codebase. preact-compat gives you the advantage of supporting the vast majority of existing React modules you might find on npm. So how do you add preact-compat to your existing React code?

Install preact-compat with npm.

npm i preact-compat

The next step is to alias preact-compat. You can do that by adding the following resolve.alias configuration to your webpack.config.js

{
  "resolve": {
    "alias": {
      "react": "preact-compat",
      "react-dom": "preact-compat"
    }
  }
}

The code block above basically translates to this — If I try to import a module called React or ReactDOM, don’t give me those modules, but instead give me what’s provided on the right hand side.

Getting started with Preact

The Preact API and developer experience is largely similar to that of React, but there are a few important differences developers should be aware of.

To demonstrate these, I built a simple app that displays recent designs using the Dribbble API. The live app can be seen here and the source code for the app can be seen in it’s Github repo.

Here, I’ll point out a few of the key differences that developers should be aware of when building with Preact.

PreactDribbble

To build the Preact app, we’ll be making use of the Preact CLI. Preact CLI is a project by the Preact team that helps developers get started with Preact easily. The Preact CLI helps you to generate a Progressive Web App and ships with features like:

  • Auto-generated Service Workers for offline caching powered by sw-precache
  • Automatic code splitting for routes.
  • PRPL pattern support for efficient loading.
  • Support for CSS Modules, LESS, Sass, Stylus; with Autoprefixer.
  • Automatic app mounting, debug helpers & Hot Module Replacement.
  • Zero-configuration pre-rendering / server-side rendering hydration

The preact-cli tool is intended to help you start writing Preact code with little or no build configuration. Install preact-cli on your computer by running the command below.

npm install -g preact-cli

Once the CLI has been installed successfully, go ahead and create a new app by running the command below in your terminal. preactdribbble is the name of the app to be created and can be called anything, the app’s name does not have to prefixed with preact .

preact create preactdribbble

This should create a new folder named preactdribble with all the files needed for the Preact app in it. Navigate into the preactdribbble folder as we’ll be working from there now. Let’s start the app and see what it looks like.


More great articles from LogRocket:


# start a live-reload/HMR dev server:
npm start

This starts up a dev server with Hot Module Reloading(HMR) at http://0.0.0.0:8080 or http://localhost:8080.


I won’t go so much into the details of building the app but I’ll will be highlighting the differences in building an app with Preact.

Use of hyperscript

import { h, Component } from 'preact';

‘h’ above, is the function that turns JSX code into Virtual DOM elements. It is a more generalized version of React.createElement

Use of preact-router

preact-router provides a <Router /> component that conditionally renders its children when the URL matches their path. It also automatically wires up <a /> elements to the router.

In the code block above, we import Link from preact-router/match. <Link> is just a normal link, but it automatically adds and removes an “active” classname to itself based on whether it matches the current URL.

The Link Component uses the traditionalhref attribute unlike React that uses the to attribute.

Use of (props, state) as arguments in render() method

In the render function, we take advantage of a feature in Preact. Parsing this.props and this.state . The destructuring assignment is used to get the shots form the state and that means when mapping we can simply do shots.map instead of this.state.shots.map . In the code block above, the data from Dribbble is used to build the interface of the app. The shot image, shot title and name of the designer is used to populate the page.

Templating

The preact-cli tool does not ship with an index.html file. This can be troublesome if there’s a need to edit or add to the index.html code. In the documentation for preact-cli , there’s a section called templates. A template is used to render the pages and the default one can be seen here. We’ll need to create the template.html inside the src folder and then run the command below to inform Preact that we’d like to use the template file.

preact watch --template src/template.html

That’s it. Those are the new things that a regular React user might find odd in React. Apart from the above, Preact uses the same API as React, the same lifecycle methods, and the same methodologies. If you’re comfortable building in React, you’ll be ready to jump right in to Preact!

So Preact or React?

The answer to the question Preact or React actually depends on your use case. A tradeoff to switching over to Preact from React is that, you’ll most likely have to do away with some features, or at least need some configuration to use some of the features that ships with React (preact-compat). An example of this is Unit Testing.

React uses a testing utility called Enzyme developed by Airbnb to test its component. Unit testing is also possible in Preact, albeit with some Webpack config and limitations.

Another thing to note is the absence of Synthetic Events in Preact. Preact’s browser support target does not require this extra overhead, therefore, Preact uses the browser’s native addEventListener for event handling. This generally leads to a codebase with less maintenance and performance concerns.

It could also be argued the removal of these features is what makes Preact a better pick of the two, because it leads to a codebase with a very small size. Preact can be considered for use cases like a self-contained web widget/embed or a Progressive Web App and in apps where performance is prioritized, because of its minimal size.

React can be used in complex apps and for building large scale apps with data that changes over time. Another advantage React has is its incredible ecosystem. There are various React packages for different use cases and a quick search on Github proves this, although the Preact plugin community has been growing.

Like I mentioned above, it all depends on your use case, if you’re looking to build a small app that does one thing very well, Preact might be what you need.

React can be used when you are looking to build heavy stuff. There’s no point in building an app with Preact and having to import like 10–15 modules because of compatibility, I think at this point, you should just build with React

Further Learning Resources

  1. Preact’s website
  2. Up and Running With Preact on egghead.io
  3. Jason’s Miller talk on the origin of Preact.

 

LogRocket: Full visibility into your production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket combines session replay, product analytics, and error tracking – empowering software teams to create the ideal web and mobile product experience. What does that mean for you?

Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay problems as if they happened in your own browser to quickly understand what went wrong.

No more noisy alerting. Smart error tracking lets you triage and categorize issues, then learns from this. Get notified of impactful user issues, not false positives. Less alerts, way more useful signal.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Yomi Eluwande JavaScript developer. Wannabe designer and Chief Procrastinator at Selar.co and worklogs.co.

Leave a Reply