### Install dependencies
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Command to install all project dependencies.
```bash
npm install
```
--------------------------------
### Benchmark Setup and Execution
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Commands to set up and run the Preact benchmark suite using PNPM.
```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
```
--------------------------------
### Component Example
Source: https://github.com/preactjs/preact/blob/main/README.md
An example of using Preact components with hooks to create a dynamic UI.
```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);
```
--------------------------------
### Example Walk-Through: Disabling Re-renders
Source: https://github.com/preactjs/preact/wiki/External-DOM-Mutations
This example demonstrates disabling re-renders for a component. The `render()` method is still called for initial mounting. After mounting, you can safely modify the DOM using `this.base`.
```javascript
class Example extends Component {
shouldComponentUpdate() {
// do not re-render via diff:
return false;
}
componentWillReceiveProps(nextProps) {
// you can do something with incoming props here if you need
}
componentDidMount() {
// now mounted, can freely modify the DOM:
let thing = document.createElement('maybe-a-custom-element');
this.base.appendChild(thing);
}
componentWillUnmount() {
// component is about to be removed from the DOM, perform any cleanup.
}
render() {
return ;
}
}
```
--------------------------------
### Example Release Notes Title
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
An example of a release notes title, including an optional creative name.
```text
10.0.0-beta.1 Los Compresseros
```
--------------------------------
### HTML Text Node Example
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
Demonstrates how HTML merges adjacent text nodes into a single text node.
```html
ab
```
--------------------------------
### Use Bound Component for Click Handling
Source: https://github.com/preactjs/preact/wiki/Extending-Component
Example of a `Link` component that extends `BoundComponent` to automatically bind its `click` method. This component opens a URL when clicked.
```javascript
class Link extends BoundComponent {
bind = ['click'];
click() {
open(this.props.href);
}
render({ children }) {
let { click } = this.binds();
return { children };
}
}
render(
Click Me,
document.body
);
```
--------------------------------
### Illustrating Current Text Hydration in Preact
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
This example shows how Preact's current text hydration works, requiring DOM mutations to split merged HTML text nodes. It demonstrates the initial state and the hydration process.
```javascript
const tree =
{"a"}{"b"}
tree.children // ["a", "b"]
scratch.innerHTML = renderToString(tree)
scratch.childNodes // ["ab"] // HTML (from SSR/prerendering) merges them together
// hydrate from the HTML:
hydrate(tree, scratch) // p.firstChild.data = "a", p.append("b")
```
--------------------------------
### Correcting Collapsed Text Nodes on Next Render
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
This example demonstrates how the next non-hydration render pass corrects the collapsed text node. It shows the mutations performed to split the merged text back into individual text nodes as defined in the Virtual DOM.
```javascript
render(
{"a"}{"b"}
) // mutations: p.firstChild.data="a", p.append("b")
```
--------------------------------
### Running Tests with Coverage Options
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Demonstrates how to run individual tests and mentions environment variables for code coverage.
```javascript
it.only('should test something', () => {
expect(1).to.equal(1);
});
```
--------------------------------
### Building and Publishing Legacy Releases
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Steps for building and publishing legacy releases (8.x), including npm publish with tags.
```bash
rm -rf dist node_modules && npm i
npm run build && npm publish
# For pre-releases:
npm publish --tag next
```
--------------------------------
### Clone the git repository
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Steps to clone the Preact repository.
```bash
git clone git@github.com:preactjs/preact.git
```
--------------------------------
### Preact Repo Structure Overview
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
An overview of the Preact repository structure, including core, addons, and demo applications.
```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
```
--------------------------------
### Basic Usage
Source: https://github.com/preactjs/preact/blob/main/README.md
Demonstrates the basic usage of Preact's render function to create and update a UI structure.
```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
```
--------------------------------
### Navigate to the cloned folder
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Command to change the directory to the cloned Preact repository.
```bash
cd preact/
```
--------------------------------
### Preact X Text Node Updates
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
Demonstrates fine-grained updates to individual text nodes in Preact X.
```javascript
render(
{"a"}{"b"}
, scratch)
render(
{"a"}{"c"}
, scratch) // p.lastChild.data = "c"
```
--------------------------------
### Preact X Granular Text Nodes
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
Shows how Preact X treats adjacent text children as separate VNodes, allowing for granular updates.
```javascript
const tree =
{"a"}{"b"}
tree.props.children // ["a", "b"]
tree._children // [{props:"a"}, {props:"b"}]
```
--------------------------------
### Preact Hydration Mismatch Tracker Prototype
Source: https://github.com/preactjs/preact/wiki/Understanding-Hydration-Mismatches
This Gist provides a prototype for tracking hydration mismatches using MutationObserver. It returns an array of mismatches with reasons and the affected DOM element.
```javascript
import { hydrate } from 'preact';
import { h } from 'preact';
const root = document.getElementById('app');
let oldHTML = root.innerHTML;
// Track mutations
const observer = new MutationObserver(mutations => {
// Filter for top-level mutations
const topLevelMutations = mutations.filter(m => m.target.parentNode === root);
// Log mismatches
topLevelMutations.forEach(m => {
console.warn('Hydration Mismatch:', {
reason: m.type === 'attributes' ? 'Attribute Change' : (m.addedNodes.length ? 'Added Node' : 'Removed Node'),
element: m.target
});
});
});
// Start observing
observer.observe(root, {
attributes: true,
childList: true,
subtree: true
});
// Perform hydration
hydrate(h('div', null, 'Hello World'), root);
// Stop observing after hydration
observer.disconnect();
// Optional: Compare HTML to see what changed
// console.log('Old HTML:', oldHTML);
// console.log('New HTML:', root.innerHTML);
```
--------------------------------
### Create a Mixed Component Base Class
Source: https://github.com/preactjs/preact/wiki/Extending-Component
Extend Preact's `Component` to support rudimentary mixins by merging properties from a `mixins` array into the component instance during construction.
```javascript
class MixedComponent extends Component {
constructor() {
super();
(this.mixins || []).forEach( m => Object.assign(this, m) );
}
}
```
--------------------------------
### Simplified State Binding with Preact's linkState()
Source: https://github.com/preactjs/preact/wiki/Linked-State
Leverage Preact's `linkState()` method on the `Component` class for concise state-to-UI binding. It automatically updates the component's state using the input's value.
```javascript
class Foo extends Component {
render({ }, { text }) {
return ;
}
}
```
--------------------------------
### Release Notes Title Format
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
The expected format for the title of release notes.
```text
Version Name
```
--------------------------------
### Incrementing Version Number
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
Instructions for incrementing the version number in package.json for a new release.
```bash
git tag 11.0.0
git push origin 11.0.0
```
--------------------------------
### Developer Authored vs. Renderer Transformation
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
This illustrates how the developer's authored JSX with adjacent text nodes is transformed by the renderer during hydration. It shows the initial state and the internal representation used by the renderer.
```javascript
// what the developer authored:
hydrate(
{"a"}{"b"}
)
// what the renderer turns it into:
hydrate(
{"ab"}{null}
)
```
--------------------------------
### Create a Bound Component Base Class
Source: https://github.com/preactjs/preact/wiki/Extending-Component
Extend Preact's `Component` to automatically bind methods listed in the `binds` property. This is useful for ensuring `this` context within event handlers.
```javascript
class BoundComponent extends Component {
// example: get bound methods
binds() {
let list = this.bind || [],
binds = this._binds;
if (!binds) {
binds = this._binds = {};
for (let i=list.length; i--; ) {
binds[list[i]] = this[list[i]].bind(this);
}
}
return binds;
}
}
```
--------------------------------
### Declarative Method Binding with ES7 Decorators
Source: https://github.com/preactjs/preact/wiki/Linked-State
Use ES7 decorators like `@bind` to declaratively bind component methods. This avoids creating new function scopes on each render, improving performance.
```javascript
class Foo extends Component {
@bind
updateText(e) {
this.setState({ text: e.target.value });
}
render({ }, { text }) {
return ;
}
}
```
--------------------------------
### Preact 8 Text Node Merging
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
Illustrates how Preact 8 merged adjacent text children into a single string.
```javascript
const tree =
{"a"}{"b"}
tree.children // ["ab"]
scratch.innerHTML = renderToString(tree)
render(tree, scratch) // no mutations, since p.firstChild.data is already "ab"
```
--------------------------------
### Changelogged CLI Command
Source: https://github.com/preactjs/preact/blob/main/CONTRIBUTING.md
The command to generate changelog entries between two tags using the changelogged CLI tool.
```bash
changelogged 10.0.0-rc.2..HEAD
```
--------------------------------
### Implement Adjacent Text Merging in toChildArray
Source: https://github.com/preactjs/preact/wiki/Hydration-Design-Documentation
This diff shows the modifications to the `toChildArray` function in Preact X to enable merging of adjacent text siblings. It converts string children to Text VNodes and appends them to the previous Text VNode if one exists.
```diff
export function toChildArray(children, callback, flattened) {
if (children == null || typeof children === 'boolean') {
/* snip */
} else if (typeof children === 'string' || typeof children === 'number') {
// this is where we convert strings to Text VNodes
- flattened.push(callback(createVNode(null, children, null, null)));
+ const len = flattened.length;
+ const last = len && flattened[len - 1];
+ // if the previous VNode is Text, append this string child to it:
+ if (last && last.type === null) {
+ // Ensure it's a string, to avoid toChildArray([1,2]) returning [3]
+ last.props += String(children);
+ }
+ else {
+ // Same as today for Text nodes not preceded by other Text:
+ flattened.push(callback(createVNode(null, children, null, null)));
+ }
} else if (children._dom != null || children._component != null) {
/* snip */
}
return flattened;
}
```
--------------------------------
### Controlled Checkbox Input in Preact
Source: https://github.com/preactjs/preact/wiki/Forms
Use this pattern for controlled checkbox inputs where the component's state dictates the checked status. Listen for 'onChange' events to update state and call 'preventDefault()' to manage the toggle manually.
```javascript
class MyForm extends Component {
toggle(e) {
e.preventDefault(); // we'll handle this, thanks
let checked = !this.state.checked;
this.setState({ checked });
}
render({ }, { checked }) {
return (