Fast 3kB alternative to React with the same modern API.
All the power of Virtual DOM components, without the overhead:
- Familiar React API & patterns: ES6 Class and Functional Components
- Extensive React compatibility via a simple preact-compat alias
- Everything you need: JSX, VDOM, React DevTools, HMR, SSR..
- A highly optimized diff algorithm and seamless Server Side Rendering
- Transparent asynchronous rendering with a pluggable scheduler
- 🆕💥 Instant no-config app bundling with Preact CLI
Preact Website ➞
💁 More information at the- Demos
- Libraries & Add-ons
- Getting Started
- Linked State
- Examples
- Extensions
- Debug Mode
- Backers
- Sponsors
- License
Preact
Preact supports modern browsers and IE9+:
Demos
Real-World Apps
- Preact Hacker News (GitHub Project)
- Play.cash 🎶 (GitHub Project)
- BitMidi 🎹 Wayback machine for free MIDI files (GitHub Project)
- Ultimate Guitar 🎸speed boosted by Preact.
- ESBench is built using Preact.
- BigWebQuiz (GitHub Project)
- Nectarine.rocks (GitHub Project) 🍑
- TodoMVC (GitHub Project)
- OSS.Ninja (GitHub Project)
- GuriVR (GitHub Project)
- Color Picker (GitHub Project) 🎨
- Offline Gallery (GitHub Project) 🎈
- Periodic Weather (GitHub Project) ☀️
- Rugby News Board (GitHub Project)
- Preact Gallery an 8KB photo gallery PWA built using Preact.
- Rainbow Explorer Preact app to translate real life color to digital color (Github project).
- YASCC Yet Another SoundCloud Client (Github project).
- Journalize 14k offline-capable journaling PWA using preact. (Github project).
Runnable Examples
- Flickr Browser (@ CodePen)
- Animating Text (@ CodePen)
- 60FPS Rainbow Spiral (@ CodePen)
- Simple Clock (@ JSFiddle)
- 3D + ThreeJS (@ CodePen)
- Stock Ticker (@ CodePen)
- Create your Own! (@ JSFiddle)
Starter Projects
- Preact Boilerplate (GitHub Project) ⚡️
- Preact Offline Starter (GitHub Project) 💯
- Preact PWA (GitHub Project) 🍔
- Parcel + Preact + Unistore Starter
- Preact Mobx Starter (GitHub Project) ☀️
- Preact Redux Example ⭐️
- Preact Redux/RxJS/Reselect Example
- V2EX Preact
- Preact Coffeescript
- Preact + TypeScript + Webpack
- 0 config => Preact + Poi
- Zero configuration => Preact + Typescript + Parcel
Libraries & Add-ons
- 🙌 preact-compat: use any React library with Preact (full example)
- 🔀 preact-context: React's
createContext
api for Preact - 📄 preact-render-to-string: Universal rendering.
- 👀 preact-render-spy: Enzyme-lite: Renderer with access to the produced virtual dom for testing.
- ➿ preact-render-to-json: Render for Jest Snapshot testing.
- 🌎 preact-router: URL routing for your components
- 📑 preact-markup: Render HTML & Custom Elements as JSX & Components
- 📡 preact-portal: Render Preact components into (a) SPACE 🌌
- 📝 preact-richtextarea: Simple HTML editor component
- 🔖 preact-token-input: Text field that tokenizes input, for things like tags
- 📇 preact-virtual-list: Easily render lists with millions of rows (demo)
- 🔁 preact-cycle: Functional-reactive paradigm for Preact
- 📐 preact-layout: Small and simple layout library
- 💭 preact-socrates: Preact plugin for Socrates
- 🚣 preact-flyd: Use flyd FRP streams in Preact + JSX
- 💬 preact-i18nline: Integrates the ecosystem around i18n-js with Preact via i18nline.
- 🔬 preact-jsx-chai: JSX assertion testing (no DOM, right in Node)
- 🎩 preact-classless-component: create preact components without the class keyword
- 🔨 preact-hyperscript: Hyperscript-like syntax for creating elements
- ✅ shallow-compare: simplified
shouldComponentUpdate
helper. - 🍧 preact-codemod: Transform your React code to Preact.
- 👷 preact-helmet: A document head manager for Preact
- 👔 preact-delegate: Delegate DOM events
- 🎨 preact-stylesheet-decorator: Add Scoped Stylesheets to your Preact Components
- 🔌 preact-routlet: Simple
Component Driven
Routing for Preact using ES7 Decorators - 📠 preact-bind-group: Preact Forms made easy, Group Events into a Single Callback
- 🐣 preact-habitat: Declarative Preact widgets renderer in any CMS or DOM host (demo).
- 🎉 proppy-preact: Functional props composition for Preact components
UI Component Libraries
Want to prototype something or speed up your development? Try one of these toolkits:
- preact-material-components: Material Design Components for Preact (website)
- preact-mdc: Material Design Components for Preact (demo)
- preact-mui: The MUI CSS Preact library.
- preact-photon: build beautiful desktop UI with photon
- preact-mdl: Material Design Lite for Preact
- preact-weui: Weui for Preact
Getting Started
💁 Note: You don't need ES2015 to use Preact... but give it a try!
The easiest way to get started with Preact is to install Preact CLI. This simple command-line tool wraps up the best possible Webpack and Babel setup for you, and even keeps you up-to-date as the underlying tools change. Best of all, it's easy to understand! It builds your app in a single command (preact build
), doesn't need any configuration, and bakes in best-practises 🙌.
The following guide assumes you have some sort of ES2015 build set up using babel and/or webpack/browserify/gulp/grunt/etc.
You can also start with preact-boilerplate or a CodePen Template.
Import what you need
The preact
module provides both named and default exports, so you can either import everything under a namespace of your choosing, or just what you need as locals:
Named:
; // Tell Babel to transform JSX into h() calls:/** @jsx h */
Default:
; // Tell Babel to transform JSX into preact.h() calls:/** @jsx preact.h */
Named imports work well for highly structured applications, whereas the default import is quick and never needs to be updated when using different parts of the library.
Instead of declaring the
@jsx
pragma in your code, it's best to configure it globally in a.babelrc
:For Babel 5 and prior:
For Babel 6:
For Babel 7:
For using Preact along with TypeScript add to
tsconfig.json
:
Rendering JSX
Out of the box, Preact provides an h()
function that turns your JSX into Virtual DOM elements (here's how). It also provides a render()
function that creates a DOM tree from that Virtual DOM.
To render some JSX, just import those two functions and use them like so:
; ;
This should seem pretty straightforward if you've used hyperscript or one of its many friends. If you're not, the short of it is that the h()
function import gets used in the final, transpiled code as a drop in replacement for React.createElement()
, and so needs to be imported even if you don't explicitly use it in the code you write. Also note that if you're the kind of person who likes writing your React code in "pure JavaScript" (you know who you are) you will need to use h()
wherever you would otherwise use React.createElement()
.
Rendering hyperscript with a virtual DOM is pointless, though. We want to render components and have them updated when data changes - that's where the power of virtual DOM diffing shines. 🌟
Components
Preact exports a generic Component
class, which can be extended to build encapsulated, self-updating pieces of a User Interface. Components support all of the standard React lifecycle methods, like shouldComponentUpdate()
and componentWillReceiveProps()
. Providing specific implementations of these methods is the preferred mechanism for controlling when and how components update.
Components also have a render()
method, but unlike React this method is passed (props, state)
as arguments. This provides an ergonomic means to destructure props
and state
into local variables to be referenced from JSX.
Let's take a look at a very simple Clock
component, which shows the current time.
; { let time = ; return <time datetime=time> time </time>; } // render an instance of Clock into <body>:;
That's great. Running this produces the following HTML DOM structure:
10:28:57 PM
In order to have the clock's time update every second, we need to know when <Clock>
gets mounted to the DOM. If you've used HTML5 Custom Elements, this is similar to the attachedCallback
and detachedCallback
lifecycle methods. Preact invokes the following lifecycle methods if they are defined for a Component:
Lifecycle method | When it gets called |
---|---|
componentWillMount |
before the component gets mounted to the DOM |
componentDidMount |
after the component gets mounted to the DOM |
componentWillUnmount |
prior to removal from the DOM |
componentWillReceiveProps |
before new props get accepted |
shouldComponentUpdate |
before render() . Return false to skip render |
componentWillUpdate |
before render() |
componentDidUpdate |
after render() |
So, we want to have a 1-second timer start once the Component gets added to the DOM, and stop if it is removed. We'll create the timer and store a reference to it in componentDidMount()
, and stop the timer in componentWillUnmount()
. On each timer tick, we'll update the component's state
object with a new time value. Doing this will automatically re-render the component.
; { super; // set initial time: thisstate = time: Date ; } { // update time every second thistimer = ; } { // stop when not renderable ; } { let time = statetime; return <span> time </span>; } // render an instance of Clock into <body>:;
Now we have a ticking clock!
Props & State
The concept (and nomenclature) for props
and state
is the same as in React. props
are passed to a component by defining attributes in JSX, state
is internal state. Changing either triggers a re-render, though by default Preact re-renders Components asynchronously for state
changes and synchronously for props
changes. You can tell Preact to render prop
changes asynchronously by setting options.syncComponentUpdates
to false
.
Linked State
One area Preact takes a little further than React is in optimizing state changes. A common pattern in ES2015 React code is to use Arrow functions within a render()
method in order to update state in response to events. Creating functions enclosed in a scope on every render is inefficient and forces the garbage collector to do more work than is necessary.
One solution to this is to bind component methods declaratively. Here is an example using decko:
@bind { this; } { return <input value=text onInput=thisupdateText />; }
While this achieves much better runtime performance, it's still a lot of unnecessary code to wire up state to UI.
Fortunately there is a solution, in the form of a module called linkstate. Calling linkState(component, 'text')
returns a function that accepts an Event and uses its associated value to update the given property in your component's state. Calls to linkState()
with the same arguments are cached, so there is no performance penalty. Here is the previous example rewritten using Linked State:
; { return <input value=text onInput= />; }
Simple and effective. It handles linking state from any input type, or an optional second parameter can be used to explicitly provide a keypath to the new state value.
Note: In Preact 7 and prior,
linkState()
was built right into Component. In 8.0, it was moved to a separate module. You can restore the 7.x behavior by using linkstate as a polyfill - see the linkstate docs.
Examples
Here is a somewhat verbose Preact <Link>
component:
{ return <a href=propshref>propschildren</a>; }
Since this is ES6/ES2015, we can further simplify:
{ return <a ... href children />; } // or, for wide-open props support: { return <a ...props />; } // or, as a stateless functional component:const Link = <a ...props> children </a>;
Extensions
It is likely that some projects based on Preact would wish to extend Component with great new functionality.
Perhaps automatic connection to stores for a Flux-like architecture, or mixed-in context bindings to make it feel more like React.createClass()
. Just use ES2015 inheritance:
{ superprops; this; } { thisbinds = {}; for let i in this thisbindsi = thisi; } // example usage { ; } { let click = thisbinds; return <span onclick= click > children </span>; }
The possibilities are pretty endless here. You could even add support for rudimentary mixins:
{ super; thismixins || ; }
Debug Mode
You can inspect and modify the state of your Preact UI components at runtime using the React Developer Tools browser extension.
- Install the React Developer Tools extension
- Import the "preact/debug" module in your app
- Set
process.env.NODE_ENV
to 'development' - Reload and go to the 'React' tab in the browser's development tools
; // Enable debug mode. You can reduce the size of your app by only including this// module in development builds. eg. In Webpack, wrap this with an `if (module.hot) {...}`// check.;
Runtime Error Checking
To enable debug mode, you need to set process.env.NODE_ENV=development
. You can do this
with webpack via a builtin plugin.
// webpack.config.js // Set NODE_ENV=development to enable error checking 'process.env': 'NODE_ENV': JSON ;
When enabled, warnings are logged to the console when undefined components or string refs are detected.
Developer Tools
If you only want to include devtool integration, without runtime error checking, you can
replace preact/debug
in the above example with preact/devtools
. This option doesn't
require setting NODE_ENV=development
.
Backers
Support us with a monthly donation and help us continue our activities. [Become a backer]
Sponsors
Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]
License
MIT