DEV Community

Cover image for Embedded UI Components with Preact
Joe Buckle
Joe Buckle

Posted on

Embedded UI Components with Preact

As a front-end developer it's quite common to be tasked with creating a new UI component for an application.

You're given access to some backend API and you have to crack on and build a UI that sits somewhere inside the website as a widget, page or whatever.

The component is complex enough that you need to manage view states, so you'd quite like a system for that.
You also like using the cleaner ES6 syntax and you're already familiar with React and JSX and all that jazz.

Now, you don't have access to the applications overarching build tools - you just need to find a way of passing some reasonably sized and efficiently written code over to the application maintainers who will factor it into their monolith 😊.

I tend to see these UI components as their own small compartmentalised applications but I am fully conscious of the increased size when shipping seemingly unnecessary frameworks in packaged code.

So React is out of the question because it's > 30kb.

I eventually discovered Preact which claimed to come in at 3kb and supports all of the Virtual DOM and State Management features of React.

I totally signed up and was not disappointed. Just set up a Webpack build environment and away you go.

How is Preact so small?

React has its own Synthetic Event System for handling events and Preact uses the browsers native addEventListener.
This could lead to a user experience penalty.

React is trying very hard (30kb + hard) to ensure a consistent feel in whatever browser it's being run in; whereas Preact has chosen to use unpredictable browser-native event listeners for a massively reduced packaged size.

More on the 'subtle' differences here - Main Differences.

What's missing?

Well, not much!

  • Proptypes (they aren't used all the time anyway)
  • Children

Conclusion

Preact is a great solution to my problem but it does look as though it might come with some UI performance trade-offs leading to an inconsistent UX.

That said, if you chose to build and embedded UI component without a framework you most likely wouldn't create your own synthetic event system for seamlessly handling differences in native events.

Preact is totally winning for me in this context 👍

Top comments (0)