Getting started with Preact JS

A tiny React alternative
Arnab Mukherjee | arnab@digit.in
If you’ve used JavaScript UI frameworks then you might have observed
that the framework is mostly the largest part of your app’s JavaScript size. In case of a particularly popular UI framework, React, this led to a bunch of developers into creating a lightweight alternative that ships with the same capabilities as React yet lets your code be the biggest part of the app.

INTRODUCTION
Preact is a 3kB alternative to React developed by Jason Miller, a developer at Google, and a bunch other contributors. Its goal was to provide the same API and features that React comes with, while being lightweight and super-fast!
It succeeds on both counts. Its speed is not only due to its small size – it is one of the fastest virtual DOM libraries out there, due to its simple and predictable diff implementation. In fact, Preact’s goals can be put across in five points:
• 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.
All the above metrics, combined with Preact’s wide support for browsers has made it very popular among
the developer community. Even companies like Housing.com, Uber and Lyft have used Preact to build mobile versions of their offerings at smaller sizes and improved performance.

PREACT VS REACT
A lot of developers swear by React for interface needs. Hence, it is pretty natural to wonder why Preact is even needed. There are a few factors that make its case.
File size
You cannot ignore the size difference between the two. React is at 45kB whereas Preact is, as we stated earlier, at 3kB. This is because Preact only keeps the essentials of React, and ditches the rest to remain lightweight.
class vs classname
In React, adding a class works something like this: # React code

Content Here

While Preact supports classname,
you can just use class for CSS classes. # Preact code

Content Here


render()
For Preact, this.props and this.state are passed to render(). To understand the difference, take a look at the code here: https://dgit.in/renderPR. As it is evident, the code looks cleaner in Preact with the removal of this.You can even take it one notch higher and use destructuring as shown here: https://dgit.in/PRDestruc.
Removal of PropTypes
Since PropTypes aren’t exactly widely used, Preact has ditched them. If you still want to use PropTypes in your development, you can do so through preact-compat or manually.
Removal of Children
Children are not necessary in Preact since props.children is always an array. React.children is supported in preact-compat.
Lack of support for Synthetic events
This has been done since Preact’s target
for browser support is not along the same lines of this extra overhead. Instead, Preact puts to use the browser’s native addEventListener for event handling. Checkout GlobalEventHandlers (https://dgit.in/GEHDOM) for a complete list of DOM event handlers.
Also, a complete implementation of events would eventually lead to more maintenance and performance concerns and a larger API, which is directly against Preact’s original goal.
Component
In Preact, components are an extendable class for building self updating, encapsulated pieces of User Interface with support for lifecycle methods. This is similar to React.Component. Check out the code here to understand it better: https://dgit.in/compPR.
COMPATIBILITY WITH REACT
To ensure compatibility with React, Preact has a package called preactcompat which is intended to function as a compatibility layer between Preactand React. Most importantly, this package makes the switch from React to Preact less jarring. It is as simple as installing and aliasing preact-compat
in your program Once you’ve done that, you can continue using React/ReactDOM code without any modifications at the workflow or codebase level. Using preactcompat brings you the advantage of being able to use most React modules that may be available on npm. So, how to add preact-compat to your existing React code? First, install it with npm.
npm i preact-compat
Then add the following resolve. alias configuration to your webpack. config.js to alias preact-compat: https://dgit.in/aliasPR. And that’s it. Now whenever you reference React or ReactDOM, it will call preact-compat.
If you’re using Browserify, aliases can be included by adding the aliasify transform. First, install the transform using this code:npm i -D aliasify Then, in your package.json, instruct aliasify to redirect react imports to preact-compat: {“aliasify”:{ “aliases”:{ “react”: “preact-compat”, “react-dom”: “preact-compat”}}}
A common use-case for preactcompat is to support React-compatible third-party modules. When using
Browserify, remember to configure the Aliasify transform to be global via the –global-transform Browserify option.
In case you plan to do it manually, which is a better way to get yourself used to preact-compat and switch to it permanently, you need to find and replace all the imports/requires in your codebase (which is essentially what an alias does for you): Find: ([‘”])react(-dom)?\1 Replace: $1preact-compat$1
AND NOW, YOUR FIRST APP
At this point, we’re assuming that you have Node and NPM installed in your machine. Now we need to install Preact-CLI, a command line based tool similar to Create React App which makes it incredibly easy to get started. Use this command to install Preact’s command line utility.
npm i -g preact-cli@latest Once that installation is complete, we move on to creating our first app. preact create default myfirst-preact-app.
The above command should create
a new directory for your app with all the required configuration and files. Here, default is the template. You can use other templates at https://github.com/preactjs-templates. Your default directory for the app should be C:\ Windows\System32\.

This is the benefit of using Preact_CLI.
It provides a pre-configured setup with most popular tools ready to be used from the get go. For example, some of the things available are CSS modules, LESS / SASS, Hot Module Reload (HMR), Progressive Web App (PWA), Service Worker for offline caching, Preact Router and many more. Check out the documentation to know more about all it can do here: https://dgit.in/CLIreadMe. It makes absolutely no sense to not use it considering the amount of time it can save. Now, lets get to running the project with the code below:
cd my-first-preact-app
# start a live-reload/HMR dev
server:
npm start
# Or
preact watch
And as the output would have told you, heading to http://0.0.0.0:8080 on your machine will show you the Preact app in its current state.

Now let us tinker around bit with this app to see how things work here. In your app’s directory, go to /routes/profile and open the index.js file in a code editor of your choice (we went with Notepad++). In this file, you’ll find code that will look pretty familiar if you’ve worked with React before.

Go to line 34 and change it as shown below:
// From

Profile: {user}

// To

Hola {user}!

Hit save and visit the original address at http://0.0.0.0:8080 again (It should refresh on its own. If it doesn’t, open the command tool where the application is running and let it rebuild). In there, click on ‘John’ to see the changes reflected.

It’s time to take our understandingof this framework one step further.
Let us add a new Component to do that. For that, you need to create a new folder, Github inside routes. Once the folder is created, create an index.js file inside it. Our objective is to create a component that will fetch the number of followers of a given user from Github’s API. The code can be found
here: https://dgit.in/gitcomp.To add some style elements, create styles.css in the same folder and add the following code in it.
.container {padding: 56px 20px; min-height: 100%; width: 100%; background: #EEE;}
As of now, the component is ready and needs to be imported. To do that, we need to connect it to routes and add it in the header for the main app for successful navigation. Go to the src folder in the root of your application’s directory and edit the index. js file. You need to replace the code in the file with the following code: https://dgit.in/CompPrec.
Following that, go to \src\components\header and edit the index.js file to add the new Link tag as follows. GithubAt this point, you may need to refresh your app to see the output but the page should eventually have a new ‘Github’ tab that should look like this.

Feel free to try it out. Pick any random user name from Github and input it here. The output should look like this:

Congratulate yourself – you’ve just built your first functional component in Preact. Seems too easy right? But we’re not done yet. There’s one more step involved for this build to be complete.
SHIP IT
Now that everything is ready, it is time to deploy your application. But before we do that, there’s a lesson to be learnt. Go to your browser’s developer tools. Since we were on Chrome, for us that meant navigating to the triple-dot menu, scrolling down to More tools and clicking on Developer tools
(the shortcut is Ctrl+Shift+I).
Navigate to the network tab and find bundle.js to note the size of the asset. You can see what our files looked like in the screenshot below. We got a file size of 181B. Note this down as it will be useful later.looked like.Now, go to the root directory for your project (the one under System32),

open a command prompt and run preact build in the command line. You should see an output that looks
something like this:

All the files generated by the above command will be present in the build folder at the root of your project.

Now it is time to check how the appworks in a production-like environment. The Preact-CLI includes a command called preact serve – which basically serves files from the build folder. After you’ve run this command, if pointing your browser to https://localhost:8080/ shows you the same app as it was in development.
EFFICIENCY
Do you remember the bundle.js size that we noted earlier? If you check it now, you should see a considerable reduction in size. We got it down to 16.9 B, which is a reduction of almost 90 percent!
IN CONCLUSION
As you can see, Preact is quite powerful and can help you make your apps faster and lighter, with the same capabilities as React. It has a growing plugin ecosystem that you can checkout
at https://dgit.in/PreactPlugins.
There are Components, Add-ons, Integrations, GUI Toolkits, Testing and Utilities, where additions are being made as we speak. Along with that, its usage and adopters are also evolving. Along with
Uber, Lyft and Housing.com mentioned earlier, companies like Tencent Pepsi, Treebo, New York Times and more have used Preact. Find the full list at https://dgit.in/PreactUseCases.
The developer community for Preact is pretty active and responsive as well. For instance, a blog post we were checking out on the topic mentioned that the creator of Preact JS, Jason Miller, had fixed a bug in Preact CLI while they were writing the article and had highlighted it to him.

If you’re interesting in pursuing further demos and examples, check out https://dgit.in/PreactDemos to see examples ranging from the Preact Website (preactjs.com) itself to GuriVR (gurivr.com) a natural language based Web VR story creator.
OTHER ALTERNATIVES TO REACT
There are other alternatives to React that can do the job as well:
• InfernoJS: The author of InfernoJS eventually joined Facebook’s React team. That should be a testament to how successful it has been. It is one of the fastest and most popular JavaScript libraries out there. It supports both JSX and hyperscript, as well as the Vanilla createElement method. Inferno also has binding support for various popular state management libraries like MobX, Redux and Cerebraljs.
• React-Lite: This one was created just to drop in as a replacement for React. While the compatibility with React is much higher than both InfernoJS and Preact, it is neither the lightest nor the fastest alternative out there. On the plus side, It can be used directly via a webpack alias without the compatibility package that the other two need.

Leave a Comment

Your email address will not be published. Required fields are marked *