preact README

The project's README from github.com/preactjs/preact. As one markdown file: README.md.

Preact

Fast 4kB alternative to React with the same modern API.

All the power of Virtual DOM components, without the overhead:

💁 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]

            SentDM Songsterr Deno

Backers

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


License

MIT

Preact

preact (preactjs/preact)

Searching Database…

38.9K ·GitHub
Что это такое?Preact — это быстрая альтернатива React размером 3 КБ, которая реализует тот же современный API, включая компоненты и Virtual DOM.
Это фреймворк или библиотека и как она связана с React?Это библиотека для отрисовки интерфейсов, а не полноценный фреймворк. Она повторяет API React (классы, хуки, функциональные компоненты) и может использоваться как прямая замена через псевдоним preact/compat.
Как добавить Preact в проект?Вы пишете компоненты и элементы с помощью JSX или шаблонов HTM (Tagged Templates), а затем вызываете функцию render(), чтобы вывести дерево компонентов в DOM-элемент.
Обязательно ли использовать JSX или есть другой синтаксис?JSX — типичный способ писать компоненты, но он не обязателен: можно использовать и HTM, который вместо этого работает со стандартными тегированными шаблонными строками JavaScript (Tagged Templates).
Мой существующий код на React просто заработает с Preact?Большинство кода на React должно работать через слой совместимости preact/compat, но это простой псевдоним, а не идеальная повторная реализация 1:1, поэтому некоторые пограничные случаи поведения, специфичного для React, могут не поддерживаться.
Поддерживает ли он серверный рендеринг и горячую перезагрузку?Да, Preact включает всё необходимое для SSR, гидратации, интеграции с DevTools и HMR из коробки.
Какие браузеры он поддерживает?Preact поддерживает все современные браузеры.
Почему Preact быстрее и легче React?Компактный размер около 3 КБ и скорость достигаются за счёт высокооптимизированного алгоритма сравнения (diff) и бесшовной гидратации, при этом сохраняется знакомая модель компонентов React.
Поддерживает ли он асинхронный рендеринг?Да, в Preact есть прозрачный асинхронный рендеринг с подключаемым планировщиком.
Где найти библиотеки и дополнения от сообщества?Список awesome-preact собирает библиотеки и инструменты от сообщества для работы с Preact.
Creator
preactjs
Size
19.6 MB
Stars
38.9K
Age
11y
Commits · 90 Days