Mallow's Blog

Preact

What is Preact ?

Preact – A lightweight alternative for React with a much smaller size and with the same modern API

It is not intended to be a reimplementation of React as it does not attempt to include every feature of React

Some of the key features of Preact includes:

  • Small Size and Big Performance
  • Closer to the DOM
  • Preact can also be used to build a small part of your existing larger application
  • React Ecosystem Compatible with preact/compat package

Lightweight alternative: what’s included and what’s not

Included

  • ES6 Class Components and Stateless Pure Functional Components
  • Virtualised DOM Diffing
  • Higher Order Components, Refs and Contexts, etc.
  • Batching of DOM updates
  • Dedicated CLI

Not Included

  • Proptype Validation
  • Children
  • Synthetic Events

Applications and Use Cases

Preact is considered to be the best choice if you are concerned with app’s performance, speed and size

It is used mainly for building PWA’s (Progressive Web Apps)

Size Comparision of React and Preact

  • React+ReactDom – 2.5KB+42KB = 44.5KB
  • Preact – 3.5KB

It is used in many companies such as Etsy, Uber, Lyft, and Smashing Magazine

Also, the learning curve for Preact is much lower due to its similarities with React

Limitations

Preact has some limitations because of the small community support with only 295+ contributors on it’s Github, whereas React has 1580+ contributors

We can use react packages only through a middle man called preact/compat, it is the compatibility layer that allows you to use libraries of the React ecosystem

As it only mimics the features of React, it doesn’t innovate the web development field and just re-invents the wheel in most cases

No Synthetic Event Handling: Preact is based on browser API and doesn’t support synthetic event handling

Counter Example

Creating the App with Preact CLI with default template

npx preact-cli create default counter-app

To run the development server

cd counter-app
num run dev

Counter example in React which uses the same hooks as React


import { useState } from "preact/hooks";

function Counter() {
  const [value, setValue] = useState(0);

  return (
    <>
      <div>Counter: {value}</div>
      <button onClick={() => setValue(value + 1)}>Increment</button>
      <button onClick={() => setValue(value - 1)}>Decrement</button>
    </>
   )
 }

Final thoughts

Both React and Preact are open-source javascript libraries used for Frontend Web Development, while React is preferred for more extensive and complex applications and Preact is used for making performant applications that are smaller in size

Even though both libraries are similar in most aspects, we can’t say that Preact can replace React, both have their pros and cons, it all comes down to your business use cases.

Pradeep Saravanan React Team

Mallow Technologies Pvt Ltd

Leave a Comment

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