JavaScript - - By Ahmed Bouchefra

Using Preact as a React Alternative

For a high-quality, in-depth introduction to React, you can’t go past Canadian full-stack developer Wes Bos. Try his course here, and use the code SITEPOINT to get 25% off and to help support SitePoint.

Preact is an implementation of the virtual DOM component paradigm just like React and many other similar libraries. Unlike React, it’s only 3KB in size, and it also outperforms it in terms of speed. It’s created by Jason Miller and available under the well-known permissive and open-source MIT license.

Why Use Preact?

Preact logoPreact is a lightweight version of React. You may prefer to use Preact as a lightweight alternative if you like building views with React but performance, speed and size are a priority for you — for example, in the case of mobile web apps or progressive web apps.

Whether you’re starting a new project or developing an existing one, Preact can save you a lot of time. You don’t need to reinvent the wheel trying to learn a new library, since it’s similar to, and compatible with, React — to the point that you can use existing React packages with it with only some aliasing, thanks to the compatibility layer preact-compat.

Pros and Cons

There are many differences between React and Preact that we can summarize in three points:

  • Features and API: Preact includes only a subset of the React API, and not all available features in React.
  • Size: Preact is much smaller than React.
  • Performance: Preact is faster than React.

Every library out there has its own set of pros and cons, and only your priorities can help you decide which library is a good fit for your next project. In this section, I’ll try to list the pros and cons of the two libraries.

Preact Pros

  • Preact is lightweight, smaller (only 3KB in size when gzipped) and faster than React (see these tests). You can also run performance tests in your browser via this link.
  • Preact is largely compatible with React, and has the same ES6 API as React, which makes it dead easy either to adopt Preact as a new library for building user interfaces in your project or to swap React with Preact for an existing project for performance reasons.
  • It has good documentation and examples available from the official website.
  • It has a powerful and official CLI for quickly creating new Preact projects, without the hassle of Webpack and Babel configuration.
  • Many features are inspired by all the work already done on React.
  • It has also its own set of advanced features independent from React, like Linked State.

React Pros

  • React supports one-way data binding.
  • It’s backed by a large company, Facebook.
  • Good documentation, examples, and tutorials on the official website and the web.
  • Large community.
  • Used on Facebook’s website, which has millions of visitors worldwide.
  • Has its own official developer debugging tools extension for Chrome.
  • It has the Create React App project boilerplate for quickly creating projects with zero configuration.
  • It has a well-architectured and complex codebase.

React Cons

  • React has a relatively large size in comparison with Preact or other existing similar libraries. (React minified source file is around 136KB in size, or about 42KB when minified and gzipped.)
  • It’s slower than Preact.
  • As a result of its complex codebase, it’s harder for novice developers to contribute.

Note: Another con I listed while writing this article was that React had a grant patent clause paired with the BSD license, making it legally unsuitable for some use cases. However, in September 2017, the React license switched MIT, which resolved these license concerns.

Preact Cons

  • Preact supports only stateless functional components and ES6 class-based component definition, so there’s no createClass.
  • No support for context.
  • No support for React propTypes.
  • Smaller community than React.

Getting Started with Preact CLI

Preact CLI is a command line tool created by Preact’s author, Jason Miller. It makes it very easy to create a new Preact project without getting bogged down with configuration complexities, so let’s start by installing it.

Open your terminal (Linux or macOS) or command prompt (Windows), then run the following commands:

npm i -g preact-cli@latest

This will install the latest version of Preact CLI, assuming you have Node and NPM installed on your local development machine.

You can now create your project with this:

preact create my-app

Or with this, ff you want to create your app interactively:

preact init

Next, navigate inside your app’s root folder and run this:

npm start

This will start a live-reload development server.

Finally, when you finish developing your app, you can build a production release using this:

npm run build

Demystifying Your First Preact App

After successfully installing the Preact CLI and generating an app, let’s try to understand the simple app generated with the Preact CLI.

The Preact CLI generates the following directory structure

├── node_modules
├── package.json
├── package-lock.json
└── src
    ├── assets
    ├── components
    │   ├── app.js
    │   └── header
    ├── index.js
    ├── lib
    ├── manifest.json
    ├── routes
    │   ├── home
    │   └── profile
    └── style
        └── index.css

The components folder holds Preact components, and the routes folder holds the page components used for each app’s route. You can use the lib folder for any external libraries, the style folder for CSS styles, and the assets for icons and other graphics.

Note the manifest.json file, which is like package.json but for PWAs (progressive web apps). Thanks to the Preact CLI, you can have a perfect-score PWA out of the box.

Now, if you open your project’s package.json file, you’ll see that the main entry point is set to src/index.js. Here is the content of this file:

import './style';
import App from './components/app';

export default App;

As you can see, index.js imports styles, and App component from ./components/app**, and then just exports it as the default.

Now, let’s see what’s inside ./components/app:

import { h, Component } from 'preact';
import { Router } from 'preact-router';

import Header from './header';
import Home from '../routes/home';
import Profile from '../routes/profile';

export default class App extends Component {
    handleRoute = e => {
        this.currentUrl = e.url;
    };

    render() {
        return (
            <div id="app">
                <Header />
                <Router onChange={this.handleRoute}>
                    <Home path="/" />
                    <Profile path="/profile/" user="me" />
                    <Profile path="/profile/:user" />
                </Router>
            </div>
        );
    }
}

This file exports a default class App which extends the Component class imported from the preact package. Every Preact component needs to extend the Component class.

App defines a render method, which returns a bunch of HTML elements and Preact components that render the app’s main user interface.

Inside the div element, we have two Preact components, Header — which renders the app’s header — and a Router component.

The Preact Router is similar to the latest version of React Router (version 4). You simply need to wrap the child components with a <Router> component, then specify the path prop for each component. Then, the router will take care of rendering the component, which has a path prop that matches the current browser’s URL.

It’s worth mentioning that Preact Router is very simple and, unlike React Router, it doesn’t support advanced features such as nested routes and view composition. If you need these features, you have to use either the React Router v3 by aliasing preact-compat, or better yet use the latest React Router (version 4) which is more powerful than v3 and doesn’t need any compatibility layer, because it works directly with Preact. (See this CodePen demo for an example.)

Preact Compatibility Layer

The preact-compat module allows developers to switch from React to Preact without changing imports from React and ReactDOM to Preact, or to use existing React packages with Preact.

Using preact-compat is easy. All you have to do is to first install it via npm:

npm i -S preact preact-compat

Then set up your build system to redirect imports or requires for react or react-dom to preact-compat. For example, in the case of Webpack, you just need to add the following configuration to webpack.config.js:

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

Recommended Courses

Wes Bos
A step-by-step training course to get you building real world React.js + Firebase apps and website components in a couple of afternoons. Use coupon code 'SITEPOINT' at checkout to get 25% off.

Conclusion

Preact is a nice alternative to React. Its community is growing steadily, and more web apps are using it. So if you’re building a web app with high-performance requirements, or a mobile app for slow 2G networks, then you should consider Preact — either as the first candidate view library for your project, or as a drop-in replacement for React.