### Install Dependencies
Source: https://github.com/tanstack/preact/blob/main/CONTRIBUTING.md
Install all necessary project dependencies using npm.
```bash
npm install
```
--------------------------------
### Manual Render Flushing with `setupRerender`
Source: https://context7.com/tanstack/preact/llms.txt
Use `setupRerender` to get a `rerender` function for manually flushing queued Preact re-renders, providing precise control over state updates during tests.
```jsx
import { render } from 'preact';
import { setupRerender } from 'preact/test-utils';
import { useState } from 'preact/hooks';
function Input() {
const [value, setValue] = useState('');
return setValue(e.currentTarget.value)} />;
}
const rerender = setupRerender();
const container = document.createElement('div');
render(, container);
const input = container.querySelector('input');
input.value = 'hello';
input.dispatchEvent(new Event('input'));
// Without calling rerender(), the DOM still shows the old value.
// Calling rerender() flushes all queued updates:
rerender();
console.log(input.value); // "hello"
```
--------------------------------
### Initializing and Updating Git Submodules for Benchmarks
Source: https://github.com/tanstack/preact/blob/main/CONTRIBUTING.md
Commands to initialize, update, and manage git submodules, specifically for the benchmarks repository. Ensure PNPM is installed before running.
```bash
pnpm -v # Make sure pnpm is installed
git submodule update --init --recursive
cd benchmarks
pnpm i
```
```bash
# In the benchmarks folder
pnpm run bench
```
```bash
git submodule update --recursive
```
```bash
git checkout --recurse-submodules
```
--------------------------------
### Example Usage of Automatic JSX Transform
Source: https://context7.com/tanstack/preact/llms.txt
Demonstrates a component using JSX with the automatic transform, eliminating the need for manual `h` imports.
```jsx
// No need for: import { h } from 'preact'
// Babel/TS automatically imports jsx/jsxs from 'preact/jsx-runtime'
function App() {
return (
Automatic JSX Transform
No manual h() import needed!
);
}
export default App;
```
--------------------------------
### Preact Repository Structure Overview
Source: https://github.com/tanstack/preact/blob/main/CONTRIBUTING.md
This bash script provides a visual overview of the Preact repository structure, highlighting core, addons, and demo directories.
```bash
# The repo root (folder where you cloned the repo into)
/
src/ # Source code of our core
test/ # Unit tests for core
dist/ # Build artifacts for publishing on npm (may not be present)
# Sub-package, can be imported via `preact/compat` by users.
# Compat stands for react-compatibility layer which tries to mirror the
# react API as close as possible (mostly legacy APIs)
compat/
src/ # Source code of the compat addon
test/ # Tests related to the compat addon
dist/ # Build artifacts for publishing on npm (may not be present)
# Sub-package, can be imported via `preact/hooks` by users.
# The hooks API is an effect based API to deal with component lifecycles.
# It's similar to hooks in React
hooks/
src/ # Source code of the hooks addon
test/ # Tests related to the hooks addon
dist/ # Build artifacts for publishing on npm (may not be present)
# Sub-package, can be imported via `preact/debug` by users.
# Includes debugging warnings and error messages for common mistakes found
# in Preact applications. Also hosts the devtools bridge
debug/
src/ # Source code of the debug addon
test/ # Tests related to the debug addon
dist/ # Build artifacts for publishing on npm (may not be present)
# Sub-package, can be imported via `preact/test-utils` by users.
# Provides helpers to make testing Preact applications easier
test-utils/
src/ # Source code of the test-utils addon
test/ # Tests related to the test-utils addon
dist/ # Build artifacts for publishing on npm (may not be present)
# A demo application that we use to debug tricky errors and play with new
# features.
demo/
# Contains build scripts and dependencies for development
package.json
```
--------------------------------
### Navigate to Preact Directory
Source: https://github.com/tanstack/preact/blob/main/CONTRIBUTING.md
Change your current directory to the cloned Preact repository folder.
```bash
cd preact/
```
--------------------------------
### setupRerender()
Source: https://context7.com/tanstack/preact/llms.txt
Manually control render flushing in tests. Returns a rerender function to manually flush queued Preact re-renders, giving precise control over when state updates are applied during tests.
```APIDOC
## setupRerender()
### Description
Manually control render flushing in tests. Returns a `rerender` function to manually flush queued Preact re-renders, giving precise control over when state updates are applied during tests.
### Usage
```jsx
import { render } from 'preact';
import { setupRerender } from 'preact/test-utils';
import { useState } from 'preact/hooks';
function Input() {
const [value, setValue] = useState('');
return setValue(e.currentTarget.value)} />;
}
const rerender = setupRerender();
const container = document.createElement('div');
render(, container);
const input = container.querySelector('input');
input.value = 'hello';
input.dispatchEvent(new Event('input'));
// Without calling rerender(), the DOM still shows the old value.
// Calling rerender() flushes all queued updates:
rerender();
console.log(input.value); // "hello"
```
```
--------------------------------
### Render and Update UI with Preact
Source: https://github.com/tanstack/preact/blob/main/README.md
Use the `render` function to create a UI tree and append it to a DOM element. Subsequent calls to `render` with the same element will update the UI efficiently.
```javascript
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(
Hello
,
document.body
);
// update the tree in-place:
render(
Hello World!
,
document.body
);
// ^ this second invocation of render(...) will use a single DOM call to update the text of the
```
--------------------------------
### Release Note Title Format
Source: https://github.com/tanstack/preact/blob/main/CONTRIBUTING.md
Follow this format for release note titles. The version name is optional.
```txt
Version Name
```
```txt
10.0.0-beta.1 Los Compresseros
```
--------------------------------
### options
Source: https://context7.com/tanstack/preact/llms.txt
A global options object that allows libraries to hook into Preact's rendering pipeline for custom lifecycle hooks.
```APIDOC
## options — Global lifecycle hooks for Preact internals
A global options object that allows libraries (devtools, hooks, compat) to hook into Preact's rendering pipeline.
```js
import { options } from 'preact';
// Called every time a VNode is created
const prevVnode = options.vnode;
options.vnode = vnode => {
if (prevVnode) prevVnode(vnode);
console.log('VNode created:', vnode.type);
};
// Custom async rendering scheduler (e.g., replace with requestIdleCallback)
options.debounceRendering = cb => {
requestIdleCallback(cb, { timeout: 100 });
};
// Intercept events before they reach handlers
options.event = e => {
console.log('Event intercepted:', e.type);
return e;
};
```
```
--------------------------------
### Clone Preact Repository
Source: https://github.com/tanstack/preact/blob/main/CONTRIBUTING.md
Use this command to clone the Preact git repository to your local machine.
```bash
git clone git@github.com:preactjs/preact.git
```
--------------------------------
### createContext
Source: https://context7.com/tanstack/preact/llms.txt
Creates a Context object that allows components to subscribe to context value changes, enabling prop drilling avoidance.
```APIDOC
## createContext(defaultValue) — Create a context for prop drilling avoidance
Creates a Context object with a Provider and Consumer. Any component in the tree can subscribe to context value changes.
```jsx
import { createContext, render } from 'preact';
import { useContext } from 'preact/hooks';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return ;
}
function App() {
return (
{/* Consumer render prop pattern */}
{theme =>
Current theme: {theme}
}
);
}
render(, document.getElementById('app'));
// ThemedButton renders with class="btn-dark"
```
```
--------------------------------
### Code-split components with Suspense and lazy
Source: https://context7.com/tanstack/preact/llms.txt
Utilize Suspense and lazy for asynchronous component loading. lazy wraps dynamic imports, and Suspense displays a fallback UI while the component is being fetched. Ensure components are imported from 'preact/compat'.
```jsx
import { render } from 'preact';
import { Suspense, lazy } from 'preact/compat';
// Dynamically imported — loaded only when needed
const HeavyChart = lazy(() => import('./components/HeavyChart'));
const AdminPanel = lazy(() => import('./components/AdminPanel'));
function Dashboard({ showAdmin }) {
return (
Dashboard
Loading chart…
}>
{showAdmin && (
Loading admin panel…}>
)}
);
}
render(, document.getElementById('app'));
```
--------------------------------
### Fragment
Source: https://context7.com/tanstack/preact/llms.txt
Renders multiple children without introducing an extra DOM element.
```APIDOC
## Fragment
### Description
Renders multiple children without introducing an extra DOM element.
### Request Example
```jsx
import { Fragment, render, h } from 'preact';
function TableRows() {
return (
h(Fragment, null,
h('tr', null, h('td', null, 'Row 1, Col 1'), h('td', null, 'Row 1, Col 2')),
h('tr', null, h('td', null, 'Row 2, Col 1'), h('td', null, 'Row 2, Col 2'))
)
);
// Shorthand: <>
}
render(
h('table', null, h('tbody', null, h(TableRows))),
document.getElementById('app')
);
```
```
--------------------------------
### memo
Source: https://context7.com/tanstack/preact/llms.txt
Wraps a functional component and performs a shallow prop comparison (or custom comparison) before deciding to re-render, optimizing performance by skipping unnecessary re-renders.
```APIDOC
## Compat API (`preact/compat`)
### `memo(component, comparer?)` — Skip re-renders when props are unchanged
Wraps a functional component and performs a shallow prop comparison (or custom comparison) before deciding to re-render.
```jsx
import { render } from 'preact';
import { useState } from 'preact/hooks';
import { memo } from 'preact/compat';
const UserCard = memo(
function UserCard({ user }) {
console.log('UserCard rendered:', user.name);
return
{/* UserCard does NOT re-render when tick changes */}
);
}
render(, document.getElementById('app'));
```
```
--------------------------------
### Create Context with createContext
Source: https://context7.com/tanstack/preact/llms.txt
Use createContext to create a context object that allows components to subscribe to context value changes, avoiding prop drilling. The returned object includes a Provider and Consumer.
```jsx
import { createContext, render } from 'preact';
import { useContext } from 'preact/hooks';
const ThemeContext = createContext('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return ;
}
function App() {
return (
{/* Consumer render prop pattern */}
{theme =>
Current theme: {theme}
}
);
}
render(, document.getElementById('app'));
// ThemedButton renders with class="btn-dark"
```
--------------------------------
### Memoize Expensive Computations with useMemo
Source: https://context7.com/tanstack/preact/llms.txt
Use useMemo to recompute a value only when its dependencies change. This avoids unnecessary recalculations on every render, improving performance for costly operations.
```jsx
import { render } from 'preact';
import { useState, useMemo } from 'preact/hooks';
function PrimeList({ limit }) {
const primes = useMemo(() => {
console.log('Computing primes up to', limit); // Only recalculates when limit changes
const result = [];
for (let n = 2; n <= limit; n++) {
if (!result.some(p => n % p === 0)) result.push(n);
}
return result;
}, [limit]);
return
Found {primes.length} primes up to {limit}: {primes.slice(0, 10).join(', ')}…
;
}
function App() {
const [limit, setLimit] = useState(100);
return (
<>
setLimit(+e.currentTarget.value)} />
>
);
}
render(, document.getElementById('app'));
```
--------------------------------
### Suspense and lazy
Source: https://context7.com/tanstack/preact/llms.txt
Enables code-splitting components with asynchronous loading. `lazy` wraps a dynamic import, and `Suspense` renders a fallback UI while the lazily loaded component is being fetched.
```APIDOC
## `Suspense` and `lazy` — Code-split components with async loading
`lazy` wraps a dynamic import and returns a component that integrates with `Suspense`. While the component loads, `Suspense` renders its `fallback`.
### Example
```jsx
import { render } from 'preact';
import { Suspense, lazy } from 'preact/compat';
// Dynamically imported — loaded only when needed
const HeavyChart = lazy(() => import('./components/HeavyChart'));
const AdminPanel = lazy(() => import('./components/AdminPanel'));
function Dashboard({ showAdmin }) {
return (
Dashboard
Loading chart…
}>
{showAdmin && (
Loading admin panel…}>
)}
);
}
render(, document.getElementById('app'));
```
```
--------------------------------
### createElement(type, props, ...children) / h(type, props, ...children)
Source: https://context7.com/tanstack/preact/llms.txt
Creates and returns a VNode. This is the function that JSX compiles to. Both `createElement` and `h` are aliases.
```APIDOC
## createElement(type, props, ...children) / h(type, props, ...children)
### Description
Creates and returns a VNode. This is the function that JSX compiles to. Both `createElement` and `h` are aliases.
### Parameters
#### Path Parameters
- **type** (string | Component) - Required - The element type or component.
- **props** (object) - Optional - The properties for the VNode.
- **children** (...any) - Optional - The children of the VNode.
### Request Example
```jsx
import { h, createElement } from 'preact';
// Using JSX (compiles to h() calls)
const vnode = h('div', { class: 'greeting' }, 'Hello ', h('span', null, 'World'));
// Equivalent without JSX
const vnode2 = createElement('div', { class: 'greeting' },
'Hello ',
createElement('span', null, 'World')
);
// With a component type
function Greeting({ name }) {
return h('p', null, `Hello, ${name}`);
}
const vnode3 = createElement(Greeting, { name: 'Preact' });
```
```
--------------------------------
### hydrate(vnode, container)
Source: https://context7.com/tanstack/preact/llms.txt
Attaches Preact to existing server-rendered HTML without re-creating DOM nodes, making hydration efficient for SSR use cases.
```APIDOC
## hydrate(vnode, container)
### Description
Attaches Preact to existing server-rendered HTML without re-creating DOM nodes, making hydration efficient for SSR use cases.
### Parameters
#### Path Parameters
- **vnode** (VNode) - Required - The virtual DOM node to hydrate.
- **container** (DOMElement) - Required - The DOM element containing server-rendered HTML.
### Request Example
```jsx
import { hydrate, h } from 'preact';
// HTML already in the document from the server:
//
Hello SSR
hyydrate(h(App), document.getElementById('app'));
// Preact walks existing DOM nodes and attaches event listeners without re-rendering
```
```
--------------------------------
### Configure Automatic JSX Transform with Babel
Source: https://context7.com/tanstack/preact/llms.txt
Configure Babel to use Preact's automatic JSX runtime for JSX without manual `h` imports.
```javascript
// babel.config.js
module.exports = {
plugins: [
['@babel/plugin-transform-react-jsx', {
runtime: 'automatic',
importSource: 'preact'
}]
]
};
```
--------------------------------
### Create a Component with State in Preact
Source: https://github.com/tanstack/preact/blob/main/README.md
Define functional components using hooks like `useState` to manage component state. This allows for dynamic and interactive user interfaces.
```javascript
import { render, h } from 'preact';
import { useState } from 'preact/hooks';
/** @jsx h */
const App = () => {
const [input, setInput] = useState('');
return (
Do you agree to the statement: "Preact is awesome"?
setInput(e.target.value)} />
);
};
render(, document.body);
```
--------------------------------
### Hydrate Server-Rendered HTML with Preact
Source: https://context7.com/tanstack/preact/llms.txt
Use `hydrate` to attach Preact to existing server-rendered HTML without re-creating DOM nodes. This is efficient for SSR use cases.
```jsx
import { hydrate } from 'preact';
// HTML already in the document from the server:
//
Hello SSR
hydrate(, document.getElementById('app'));
// Preact walks existing DOM nodes and attaches event listeners without re-rendering
```
--------------------------------
### Mount, Update, and Unmount a Preact Tree
Source: https://context7.com/tanstack/preact/llms.txt
Use `render` to mount a Preact component tree into a DOM element. Subsequent calls with the same container update the tree efficiently. Pass `null` to unmount.
```jsx
import { render, h } from 'preact';
// First render — mounts the app
render(
Hello, World!
, document.getElementById('app'));
// Second render on the same container — diffs and patches only the changed parts
render(
Hello, Preact!
, document.getElementById('app'));
// Unmount
render(null, document.getElementById('app'));
```
--------------------------------
### useId
Source: https://context7.com/tanstack/preact/llms.txt
Generates a stable, unique ID for accessibility purposes, ensuring consistency between server and client renders.
```APIDOC
## `useId()` — Generate a stable unique ID
Generates a stable, unique ID for accessibility purposes (linking `