Convert Figma logo to code with AI

preactjs logopreact

⚛️ Fast 3kB React alternative with the same modern API. Components & Virtual DOM.

36,546
1,943
36,546
222

Top Related Projects

227,213

The library for web and native user interfaces.

207,677

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

95,657

Deliver web apps with confidence 🚀

78,194

Cybernetically enhanced web apps

32,037

A declarative, efficient, and flexible JavaScript library for building user interfaces.

16,049

:fire: An extremely fast, React-like JavaScript library for building modern user interfaces

Quick Overview

Preact is a fast, lightweight alternative to React with the same modern API. It's a 3kB JavaScript library for building user interfaces, offering a thin Virtual DOM abstraction and focusing on performance and size efficiency.

Pros

  • Extremely small bundle size (3kB) compared to React, leading to faster load times
  • Highly compatible with the React ecosystem, allowing easy migration and use of React libraries
  • Excellent performance due to its lightweight nature and efficient diff algorithm
  • Simple and straightforward API, making it easy to learn and use

Cons

  • Smaller community and ecosystem compared to React
  • Some advanced React features may not be available or require additional configuration
  • Potential compatibility issues with certain React libraries or tools
  • Less suitable for very large, complex applications where React's full feature set might be beneficial

Code Examples

  1. Basic component creation:
import { h, render } from 'preact';

function Hello({ name }) {
  return <h1>Hello, {name}!</h1>;
}

render(<Hello name="World" />, document.body);
  1. Using hooks for state management:
import { h, render } from 'preact';
import { useState } from 'preact/hooks';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

render(<Counter />, document.body);
  1. Creating a custom hook:
import { useState, useEffect } from 'preact/hooks';

function useWindowSize() {
  const [size, setSize] = useState([window.innerWidth, window.innerHeight]);

  useEffect(() => {
    const handleResize = () => setSize([window.innerWidth, window.innerHeight]);
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  return size;
}

Getting Started

To start using Preact in your project:

  1. Install Preact:

    npm install preact
    
  2. Create a new JavaScript file (e.g., app.js) and add the following code:

    import { h, render } from 'preact';
    
    function App() {
      return <h1>Hello, Preact!</h1>;
    }
    
    render(<App />, document.body);
    
  3. Set up a build process using tools like Webpack or Parcel to compile your JSX code.

  4. Include the compiled JavaScript in your HTML file and run your application.

Competitor Comparisons

227,213

The library for web and native user interfaces.

Pros of React

  • Larger ecosystem and community support
  • More comprehensive documentation and learning resources
  • Better tooling and developer experience with Create React App

Cons of React

  • Larger bundle size, which can impact performance
  • Steeper learning curve, especially for beginners
  • More complex API and lifecycle methods

Code Comparison

React:

import React from 'react';

function App() {
  return <h1>Hello, World!</h1>;
}

Preact:

import { h } from 'preact';

function App() {
  return <h1>Hello, World!</h1>;
}

The syntax is very similar, with the main difference being the import statement. React requires importing the React object, while Preact uses a named import for the h function.

Both React and Preact are popular choices for building user interfaces, with React being more widely adopted and feature-rich, while Preact focuses on a smaller footprint and faster performance. The choice between them often depends on project requirements, team expertise, and performance considerations.

207,677

This is the repo for Vue 2. For Vue 3, go to https://github.com/vuejs/core

Pros of Vue

  • More comprehensive ecosystem with official router, state management, and CLI tools
  • Better documentation and learning resources for beginners
  • Larger community and job market

Cons of Vue

  • Larger bundle size, which can impact initial load times
  • Steeper learning curve due to more concepts and API surface area
  • Less suitable for extremely performance-critical applications

Code Comparison

Vue:

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue!'
    }
  }
}
</script>

Preact:

import { h, Component } from 'preact';

class App extends Component {
  render() {
    return <div>Hello Preact!</div>;
  }
}

Vue uses a template-based approach with separate script and template sections, while Preact uses JSX for a more React-like syntax. Vue's component structure is more verbose but provides clear separation of concerns. Preact's approach is more concise and familiar to React developers.

Both frameworks offer reactive components and efficient rendering, but Preact's smaller size and closer alignment with standard DOM APIs can lead to better performance in some scenarios. Vue's additional features and tooling make it more suitable for larger applications, while Preact excels in lightweight and performance-critical projects.

95,657

Deliver web apps with confidence 🚀

Pros of Angular

  • Comprehensive framework with built-in tools for routing, forms, and HTTP requests
  • Powerful dependency injection system for better modularity and testability
  • TypeScript support out of the box, providing strong typing and improved tooling

Cons of Angular

  • Steeper learning curve due to its complexity and size
  • Larger bundle size, which can impact initial load times
  • More opinionated structure, potentially limiting flexibility in some cases

Code Comparison

Angular:

@Component({
  selector: 'app-root',
  template: '<h1>{{title}}</h1>'
})
export class AppComponent {
  title = 'Hello, Angular!';
}

Preact:

import { h, render } from 'preact';

const App = () => <h1>Hello, Preact!</h1>;
render(<App />, document.body);

Angular provides a more structured approach with decorators and TypeScript, while Preact offers a simpler, lightweight solution closer to vanilla JavaScript. Angular's component definition includes metadata, whereas Preact's functional component is more concise. Both achieve similar results, but Angular's approach is more verbose and feature-rich, while Preact focuses on simplicity and small bundle size.

78,194

Cybernetically enhanced web apps

Pros of Svelte

  • Smaller bundle sizes due to compile-time optimization
  • More intuitive syntax with less boilerplate code
  • Built-in state management and animation capabilities

Cons of Svelte

  • Smaller ecosystem and community compared to Preact
  • Less suitable for incremental adoption in existing projects
  • Requires a build step, which can complicate development setup

Code Comparison

Svelte component:

<script>
  let count = 0;
  const increment = () => count += 1;
</script>

<button on:click={increment}>
  Clicks: {count}
</button>

Preact component:

import { useState } from 'preact/hooks';

export default function Counter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(count + 1);
  return <button onClick={increment}>Clicks: {count}</button>;
}

Both Svelte and Preact are lightweight alternatives to React, but they take different approaches. Svelte compiles your code to efficient JavaScript at build time, while Preact aims to be a smaller, faster React-like library. Svelte's syntax is often more concise, but Preact offers better compatibility with the React ecosystem. The choice between them depends on project requirements, team familiarity, and performance needs.

32,037

A declarative, efficient, and flexible JavaScript library for building user interfaces.

Pros of Solid

  • Better performance due to fine-grained reactivity
  • No virtual DOM, resulting in faster updates and less memory usage
  • More flexible and powerful reactive primitives

Cons of Solid

  • Smaller ecosystem and community compared to Preact
  • Steeper learning curve for developers familiar with React-like libraries
  • Less mature, with potential for more frequent breaking changes

Code Comparison

Preact:

import { h, render } from 'preact';

function App() {
  return <h1>Hello, World!</h1>;
}

render(<App />, document.body);

Solid:

import { render } from 'solid-js/web';

function App() {
  return <h1>Hello, World!</h1>;
}

render(() => <App />, document.body);

Both Preact and Solid aim to provide lightweight alternatives to React, but they take different approaches. Preact focuses on maintaining React-like API and compatibility, while Solid introduces a new reactive system for better performance. Solid's fine-grained reactivity can lead to more efficient updates, but it may require developers to learn new concepts. Preact, on the other hand, offers a more familiar experience for React developers and has a larger ecosystem. The choice between the two depends on specific project requirements, performance needs, and team expertise.

16,049

:fire: An extremely fast, React-like JavaScript library for building modern user interfaces

Pros of Inferno

  • Faster rendering performance, especially for large and complex applications
  • More flexible architecture, allowing for easier integration with existing projects
  • Better support for isomorphic/universal JavaScript applications

Cons of Inferno

  • Smaller community and ecosystem compared to Preact
  • Less direct compatibility with React libraries and components
  • Steeper learning curve for developers coming from React

Code Comparison

Inferno:

import { render } from 'inferno';

function MyComponent({ name }) {
  return <div>Hello, {name}!</div>;
}

render(<MyComponent name="World" />, document.getElementById('app'));

Preact:

import { render } from 'preact';

function MyComponent({ name }) {
  return <div>Hello, {name}!</div>;
}

render(<MyComponent name="World" />, document.getElementById('app'));

Both Inferno and Preact aim to provide lightweight alternatives to React, with similar syntax and APIs. The code examples above demonstrate the similarity in basic component creation and rendering. The main differences lie in their internal implementations, performance optimizations, and ecosystem support.

Inferno focuses on high-performance rendering and flexibility, making it suitable for complex applications and integration with existing projects. Preact, on the other hand, prioritizes React compatibility and a smaller learning curve, making it an easier choice for developers already familiar with React.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Preact

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, hooks, and Functional Components
  • Extensive React compatibility via a simple preact/compat alias
  • Everything you need: JSX, VDOM, DevTools, HMR, SSR.
  • Highly optimized diff algorithm and seamless hydration from Server Side Rendering
  • Supports all modern browsers and IE11
  • Transparent asynchronous rendering with a pluggable scheduler

💁 More information at the Preact Website ➞

npm Preact Slack Community OpenCollective Backers OpenCollective Sponsors

coveralls gzip size brotli size

You can find some awesome libraries in the awesome-preact list :sunglasses:


Getting Started

💁 Note: You don't need ES2015 to use Preact... but give it a try!

Tutorial: Building UI with Preact

With Preact, you create user interfaces by assembling trees of components and elements. Components are functions or classes that return a description of what their tree should output. These descriptions are typically written in JSX (shown underneath), or HTM which leverages standard JavaScript Tagged Templates. Both syntaxes can express trees of elements with "props" (similar to HTML attributes) and children.

To get started using Preact, first look at the render() function. This function accepts a tree description and creates the structure described. Next, it appends this structure to a parent DOM element provided as the second argument. Future calls to render() will reuse the existing tree and update it in-place in the DOM. Internally, render() will calculate the difference from previous outputted structures in an attempt to perform as few DOM operations as possible.

import { h, render } from 'preact';
// Tells babel to use h for JSX. It's better to configure this globally.
// See https://babeljs.io/docs/en/babel-plugin-transform-react-jsx#usage
// In tsconfig you can specify this with the jsxFactory
/** @jsx h */

// create our tree and append it to document.body:
render(
	<main>
		<h1>Hello</h1>
	</main>,
	document.body
);

// update the tree in-place:
render(
	<main>
		<h1>Hello World!</h1>
	</main>,
	document.body
);
// ^ this second invocation of render(...) will use a single DOM call to update the text of the <h1>

Hooray! render() has taken our structure and output a User Interface! This approach demonstrates a simple case, but would be difficult to use as an application grows in complexity. Each change would be forced to calculate the difference between the current and updated structure for the entire application. Components can help here – by dividing the User Interface into nested Components each can calculate their difference from their mounted point. Here's an example:

import { render, h } from 'preact';
import { useState } from 'preact/hooks';

/** @jsx h */

const App = () => {
	const [input, setInput] = useState('');

	return (
		<div>
			<p>Do you agree to the statement: "Preact is awesome"?</p>
			<input value={input} onInput={e => setInput(e.target.value)} />
		</div>
	);
};

render(<App />, document.body);

Sponsors

Become a sponsor and get your logo on our README on GitHub with a link to your site. [Become a sponsor]

           

Backers

Support us with a monthly donation and help us continue our activities. [Become a backer]


License

MIT

Preact

NPM DownloadsLast 30 Days