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 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"
}
}
}
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.
Frequently Asked Questions (FAQs) about Using Preact as a React Alternative
What are the main differences between Preact and React?
Preact and React are both JavaScript libraries for building user interfaces, but they have some key differences. Preact is much smaller in size, making it faster and more efficient. It also has a simpler, more straightforward API. However, React has a larger community and more resources available, which can be beneficial for complex projects.
How does Preact improve performance compared to React?
Preact is designed to be a lightweight version of React. It’s just 3kB in size, which makes it load faster and use less memory. This can lead to improved performance, especially on mobile devices or slow networks. Preact also eliminates some of the abstraction in React, which can make your code run more efficiently.
Can I use existing React components in Preact?
Yes, you can use existing React components in Preact. Preact provides a compatibility layer called “preact-compat” that allows you to use React components and modules directly in your Preact project. This makes it easy to switch from React to Preact, or to use components from both libraries in the same project.
What are the limitations of Preact compared to React?
While Preact is smaller and faster than React, it does have some limitations. It doesn’t support some of the more advanced features of React, like the context API and certain lifecycle methods. However, many of these features can be added with plugins or workarounds.
How does Preact handle state management?
Preact handles state management in a similar way to React. You can use the setState
method to update the state of a component, and Preact will automatically re-render the component when the state changes. Preact also supports using Redux for state management, just like React.
Can I use Preact with TypeScript?
Yes, you can use Preact with TypeScript. Preact provides TypeScript definitions out of the box, so you can take advantage of static typing and other TypeScript features in your Preact projects.
How does Preact handle server-side rendering?
Preact supports server-side rendering through the preact-render-to-string
module. This allows you to render your Preact components to HTML on the server, which can improve performance and SEO.
How do I migrate from React to Preact?
Migrating from React to Preact is relatively straightforward. You can use the “preact-compat” compatibility layer to use your existing React components in Preact. You may also need to make some minor changes to your build configuration and code to accommodate the differences between React and Preact.
What is the future of Preact?
Preact is actively maintained and continues to evolve. The developers are focused on keeping Preact small and efficient, while also adding new features and improvements. Preact is also gaining popularity in the JavaScript community, so it’s likely to continue to grow and evolve in the future.
How does Preact compare to other React alternatives?
Preact is one of the most popular alternatives to React, but there are others as well, such as Inferno and Vue.js. Each of these libraries has its own strengths and weaknesses, so the best choice depends on your specific needs and preferences. Preact stands out for its small size and efficiency, as well as its compatibility with React.
Ahmed is a technical author and web developer living in Morocco with a Master's degree in software development. He authors technical content about JavaScript, Angular and Ionic. He is also a fan of entrepreneurship, poetry, and teaching. You can contact me on my personal website and read my other articles on Techiediaries.