diff --git a/package.json b/package.json
index 1750c792b5..12490bbf1e 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,8 @@
"build:lunaria": "lunaria build",
"preview:lunaria": "lunaria preview",
"check:lint": "eslint .",
- "check:types": "tsc --noEmit"
+ "check:types": "tsc --noEmit",
+ "generate:llms": "node scripts/generate-llms.mjs"
},
"dependencies": {
"@kobalte/core": "^0.13.9",
diff --git a/public/llms.txt b/public/llms.txt
new file mode 100644
index 0000000000..49056a0cc1
--- /dev/null
+++ b/public/llms.txt
@@ -0,0 +1,9121 @@
+---
+title: Fine-grained reactivity
+---
+
+Reactivity ensures automatic responses to data changes, eliminating the need for manual updates to the user interface (UI).
+By connecting UI elements to the underlying data, updates become automated.
+In a fine-grained reactive system an application will now have the ability to make highly _targeted and specific_ updates.
+
+An example of this can be seen in the contrast between Solid and [React](https://react.dev/).
+In Solid, updates are made to the targeted attribute that needs to be changed, avoiding broader and, sometimes unnecessary, updates.
+In contrast, React would re-execute an entire component for a change in the single attribute, which can be less efficient.
+
+Because of the fine-grained reactive system, unnecessary recalculations are avoided.
+Through targeting only the areas of an application that have changed the user experience becomes smoother and more optimized.
+
+**Note:** If you're new to the concept of reactivity and want to learn the basics, consider starting with our [intro to reactivity guide](/concepts/intro-to-reactivity).
+
+## Reactive primitives
+
+In Solid's reactivity system, there are two key elements: signals and observers.
+These core elements serve as the foundation for more specialized reactive features:
+
+- [Stores](/concepts/stores) which are [proxies](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) that create, read, and write signals under the hood.
+- [Memos](/concepts/derived-values/memos) resemble [effects](/concepts/effects) but are distinct in that they _return_ a signal and optimize computations through caching.
+ They update based on the behavior of effects, but are more ideal for computational optimization.
+- [Resources](/guides/fetching-data), building on the concept of memos, convert the asynchronicity of network requests into synchronicity, where the results are embedded within a signal.
+- Render effects are a tailored type of effect that initiate immediately, specifically designed for managing the rendering process.
+
+### Understanding signals
+
+[Signals](/concepts/signals) are like mutable variables that can point to a value now and another in the future.
+They are made up of two primary functions:
+
+- **Getter**: how to read the current value of a signal.
+- **Setter**: a way to modify or update a signal's value.
+
+In Solid, the [`createSignal`](/reference/basic-reactivity/create-signal) function can be used to create a signal.
+This function returns the getter and setter as a pair in a two-element array, called a tuple.
+
+```js
+import { createSignal } from "solid-js";
+
+const [count, setCount] = createSignal(1);
+
+console.log(count()); // prints "1"
+
+setCount(0); // changes count to 0
+
+console.log(count()); // prints "0"
+```
+
+Here, `count` serves as the getter, and `setCount` functions as the setter.
+
+### Effects
+
+[Effects](/concepts/effects) are functions that are triggered when the signals they depend on point to a different value.
+They can be thought of as automated responders where any changes in the signal's value will trigger the effect to run.
+
+```jsx
+import { createSignal, createEffect } from "solid-js";
+
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log(count());
+});
+```
+
+The effect takes a function that is called whenever _any_ of the signals it relies on changes, such as `count` in this example.
+
+## Building a reactive system
+
+To grasp the concept of reactivity, it is often helpful to construct a reactive system from scratch.
+
+The following example will follow the observer pattern, where data entities (signals) will maintain a list of their subscribers (effects).
+This is a way to notify subscribers whenever a signal they observe changes.
+
+Here is a basic code outline to begin:
+
+```jsx
+function createSignal() {}
+
+function createEffect() {}
+
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log("The count is " + count());
+});
+```
+
+## Reactive primitives
+
+### `createSignal`
+
+The `createSignal` function performs two main tasks:
+
+1. Initialize the value (in this case, `count` is set to `0`).
+2. Return an array with two elements: the getter and setter function.
+
+```tsx
+function createSignal(initialValue) {
+ let value = initialValue;
+
+ function getter() {
+ return value;
+ }
+
+ function setter(newValue) {
+ value = newValue;
+ }
+
+ return [getter, setter];
+}
+
+// ..
+```
+
+This allows you to retrieve the current value through the getter and make any changes via the setter.
+At this stage, reactivity is not present, however.
+
+### `createEffect`
+
+`createEffect` defines a function that immediately calls the function that is passed into it:
+
+```jsx
+// ..
+
+function createEffect(fn) {
+ fn();
+}
+
+// ..
+```
+
+### Making a system reactive
+
+Reactivity emerges when linking `createSignal` and `createEffect` and this happens through:
+
+1. Maintaining a reference to the current subscriber's function.
+2. Registering this function during the creation of an effect.
+3. Adding the function to a subscriber list when accessing a signal.
+4. Notifying all subscribers when the signal has updated.
+
+```jsx
+let currentSubscriber = null;
+
+function createSignal(initialValue) {
+ let value = initialValue;
+ const subscribers = new Set();
+
+ function getter() {
+ if (currentSubscriber) {
+ subscribers.add(currentSubscriber);
+ }
+ return value;
+ }
+
+ function setter(newValue) {
+ if (value === newValue) return; // if the new value is not different, do not notify dependent effects and memos
+ value = newValue;
+ for (const subscriber of subscribers) {
+ subscriber(); //
+ }
+ }
+
+ return [getter, setter];
+}
+
+// creating an effect
+function createEffect(fn) {
+ const previousSubscriber = currentSubscriber; // Step 1
+ currentSubscriber = fn;
+ fn();
+ currentSubscriber = previousSubscriber;
+}
+
+//..
+```
+
+A variable is used to hold a reference to the current executing subscriber function.
+This is used to determine which effects are dependent on which signals.
+
+Inside `createSignal`, the initial value is stored and a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) is used to store any subscriber functions that are dependent on the signal.
+This function will then return two functions for the signal:
+
+- The `getter` function checks to see if the current subscriber function is being accessed and, if it is, adds it to the list of subscribers before returning the _current_ value of the signal.
+- The `setter` function evaluated the new value against the old value, notifying the dependent functions only when the signal has been updated.
+
+When creating the `createEffect` function, a reference to any previous subscribers is initialized to handle any possible nested effects present.
+The current subscriber is then passed to the given function, which is run immediately.
+During this run, if the effect accesses any signals it is then registered as a subscriber to those signals.
+The current subscriber, once the given function has been run, will be reset to its previous value so that, if there are any nested effects, they are operated correctly.
+
+### Validating the reactive system
+
+To validate the system, increment the `count` value at one-second intervals:
+
+```jsx
+//..
+
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log("The count is " + count());
+});
+
+setInterval(() => {
+ setCount(count() + 1);
+}, 1000);
+```
+
+This will display the incremented count value on the console at one-second intervals to confirm the reactive system's functionality.
+
+## Managing lifecycles in a reactive system
+
+In reactive systems, various elements, often referred to as "nodes", are interconnected.
+These nodes can be signals, effects, or other reactive primitives.
+They serve as the individual units that collectively make up the reactive behavior of the system.
+
+When a node changes, the system will re-evaluate the parts connected to that node.
+This can result in updates, additions, or removals of these connections, which affect the overall behavior of the system.
+
+Now, consider a scenario where a condition influences the data used to calculate an output:
+
+```jsx
+// Temperature.jsx
+console.log("1. Initialize");
+const [temperature, setTemperature] = createSignal(72);
+const [unit, setUnit] = createSignal("Fahrenheit");
+const [displayTemp, setDisplayTemp] = createSignal(true);
+
+const displayTemperature = createMemo(() => {
+ if (!displayTemp()) return "Temperature display is off";
+ return `${temperature()} degrees ${unit()}`;
+});
+
+createEffect(() => console.log("Current temperature is", displayTemperature()));
+
+console.log("2. Turn off displayTemp");
+setDisplayTemp(false);
+
+console.log("3. Change unit");
+setUnit("Celsius");
+
+console.log("4. Turn on displayTemp");
+setDisplayTemp(true);
+```
+
+In this example, the `createMemo` primitive is used to cache the state of a computation.
+This means the computation doesn't have to be re-run if its dependencies remain unchanged.
+
+The `displayTemperature` memo has an early return condition based on the value of `displayTemp`.
+When `displayTemp` is false, the memo returns a message saying "Temperature display is off," and as a result, `temperature` and `unit` are not tracked.
+
+If the `unit` is changed while `displayTemp` is false, however, the effect won't trigger since none of the memo's current dependencies (`displayTemp` in this case) have changed.
+
+### Synchronous nature of effect tracking
+
+The reactivity system described above operates synchronously.
+This operation has implications for how effects and their dependencies are tracked.
+Specifically, the system registers the subscriber, runs the effect function, and then unregisters the subscriber — all in a linear, synchronous sequence.
+
+Consider the following example:
+
+```jsx
+createEffect(() => {
+ setTimeout(() => {
+ console.log(count());
+ }, 1000);
+});
+```
+
+The `createEffect` function in this example, initiates a `setTimeout` to delay the console log.
+Because the system is synchronous, it doesn't wait for this operation to complete.
+By the time the `count` getter is triggered within the `setTimeout`, the global scope no longer has a registered subscriber.
+As a result, this `count` signal will not add the callback as a subscriber which leads to potential issues with tracking the changes to `count`.
+
+### Handling asynchronous effects
+
+While the basic reactivity system is synchronous, frameworks like Solid offer more advanced features to handle asynchronous scenarios.
+For example, the `on` function provides a way to manually specify the dependencies of an effect.
+This is particularly useful for to make sure asynchronous operations are correctly tied into the reactive system.
+
+Solid also introduces the concept of resources for managing asynchronous operations.
+Resources are specialized reactive primitives that convert the asynchronicity of operations like network requests into synchronicity, embedding the results within a signal.
+The system can then track asynchronous operations and their state, keeping the UI up-to-date when the operation completes or its' state changes.
+
+Using resources in Solid can assist in complex scenarios when multiple asynchronous operations are involved and the completion may affect different parts of the reactive system.
+By integrating resources into the system, you can ensure that dependencies are correctly tracked and that the UI remains consistent with the underlying asynchronous data.
+
+
+---
+title: Basics
+order: 4
+---
+
+Components are the building blocks of Solid applications.
+These units are reusable and can be combined to create more complex applications.
+
+Components are functions that return [JSX](/concepts/understanding-jsx) elements:
+
+```tsx
+function MyComponent() {
+ return
Hello World
;
+}
+```
+
+A component can be as simple as a single element or as complex as a full page.
+They can also be nested within each other to create more intricate applications:
+
+```tsx
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+## Component trees
+
+A web page is displayed by rendering a component tree, which is a hierarchical structure of components.
+At the top of the tree is the primary application component, which is the root of the tree.
+Child components are nested within the primary component, and those components can have their own child components.
+This nesting can continue as needed.
+
+A simple application may have a component tree that looks like this:
+
+```json
+App // primary application component
+└── MyComponent // child component
+```
+
+When an application grows, the component tree can become more complex.
+For example, a more complex application may have a component tree that looks like this:
+
+```json
+App
+├── Header
+├── Sidebar
+├── Content
+│ ├── Post
+│ │ ├── PostHeader
+│ │ ├── PostContent
+│ │ └── PostFooter
+│ ├── Post
+│ │ ├── PostHeader
+│ │ ├── PostContent
+│ │ └── PostFooter
+│ └── Post
+│ ├── ...
+└── Footer
+```
+
+In nesting components, you can create a hierarchy of components that can be reused throughout the application.
+This allows for a more modular approach to building applications, as components can be reused in different contexts.
+
+## Component lifecycles
+
+Components have a lifecycle that defines how they are created, updated, and destroyed.
+A Solid component's lifecycle is different from other frameworks, as it is tied to the [concept of reactivity](/concepts/intro-to-reactivity).
+
+Where frameworks may re-run components on every state change, a Solid component's lifecycle is tied to its initial run.
+What this means is that a Solid component is only run once, when it is first rendered into the DOM.
+After that, the component is not re-run, even if the application's state changes.
+
+When the Solid component renders, it sets up a reactive system that monitors for state changes.
+When a state change occurs, the component will update the relevant areas without re-running the entire component.
+By bypassing the full component lifecycle on every state change, Solid has a more predictable behavior compared to frameworks that re-run functions on every update.
+
+Since the component's logic is not continuously visited, getting this setup right is important when working with Solid.
+
+### Initialization & configuration
+
+When a component is first rendered into the DOM, the component function is executed.
+This is where you will set up the component's state and side-effects.
+This includes setting up [signals](/concepts/signals), [stores](/concepts/stores), [effects](/concepts/effects), and other reactive elements.
+Since the logic in the component function is not continuously visited, it is important to set up the component correctly from the outset.
+
+Each component instance is independent of other instances, meaning that each component has its own state and side-effects.
+Through establishing proper dependencies, you can ensure that the component is set up correctly.
+This allows for components to be reused in different contexts without affecting each other.
+
+```tsx
+function MyComponent() {
+ const [count, setCount] = createSignal(0);
+
+ console.log(count());
+
+ return (
+
+
Count: {count()}
+
+
+ );
+}
+```
+
+When this component is rendered into the DOM, the function body is executed.
+This includes creating the `count` signal and executing the `console.log(count())` statement, which will log the current value of `count` to the console.
+In addition, the component's JSX is returned, which will be rendered into the DOM.
+
+After the component is rendered, the `console.log` statement will not be executed again, even if the component's state changes.
+However, because the component's JSX is reactive, each press of the button will update the DOM with the new value of `count`.
+
+In essence, Solid splits the concerns:
+
+1. The initial setup logic, which is executed once when the component is rendered.
+2. The reactive logic, which is executed when the component's state changes.
+
+### Conditional rendering
+
+To display different content based on state or other criteria, you can use conditional rendering.
+Given that the component function is only executed once, conditional statements must be placed within the return statement.
+This design ensures that conditional paths are clear and immediately understood.
+
+```tsx
+function MyComponent() {
+ const [count, setCount] = createSignal(0);
+ return (
+
+ {count() > 5 ? (
+
Count limit reached
+ ) : (
+ <>
+
Count: {count()}
+
+ >
+ )}
+
+ );
+}
+```
+
+This example uses a [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator) to conditionally render different content based on the value of `count`.
+When `count` is greater than 5, the component will display `"Count limit reached"`.
+Otherwise, it will display the current count with an increment button.
+
+
+To simplify conditional rendering, Solid provides built-in [control-flow](/concepts/control-flow/conditional-rendering) components like [`Show`](/concepts/control-flow/conditional-rendering#show), which create a more readable conditional rendering experience.
+
+ ```tsx
+ function MyComponent() {
+ const [count, setCount] = createSignal(0)
+
+ return (
+
+ 5}
+ fallback={
+ <>
+
Count: {count()}
+
+ >
+ }
+ >
+
Count limit reached
+
+
+ )
+ }
+ ```
+
+
+
+## Importing and exporting
+
+For components to be reusable, they need to be exported from one module and imported into another.
+This allows for components to be shared and used where needed.
+
+### Exporting components
+
+Once defined, a component can be [exported](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export) to make it available for use in other parts of your application.
+There are two ways to export a component: [named exports](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export#named_exports) and [default exports](https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export#default_exports).
+
+**Named export:**
+
+Named exports allow for multiple components to be exported from a single file.
+To export a component, you must use the `export` keyword before the function definition or specify the name of the component to export in curly braces (`{}`).
+
+```typescript
+export function MyComponent() {
+ return
Hello World
+}
+
+// or
+
+function MyComponent() {
+ return
Hello World
+}
+
+export { MyComponent }
+```
+
+**Default export:**
+
+Default exports specify a single component to export from a file.
+This is done by using the `default` keyword.
+
+```typescript
+// MyComponent.ts
+export default function MyComponent() {
+ return
Hello World
+}
+```
+
+### Importing components
+
+To use a component in another file or component, it must be [imported](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import).
+To import a component, you must specify the path to the file containing the component and the name of the component to import.
+
+**Named import:**
+
+When importing a named export, you must specify the name of the component to import in curly braces (`{}`).
+
+```tsx
+// App.ts
+import { MyComponent } from "./MyComponent";
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+This is the preferred way to import components, as it allows for better code readability and maintainability.
+Additionally, it allows for multiple components to be imported from the same file.
+
+```tsx
+// App.ts
+import { MyComponent, MyOtherComponent } from "./MyComponent";
+
+function App() {
+ return (
+
+
+
+
+ );
+}
+```
+
+**Default import:**
+
+To import a default export, you must specify the name of the component to import.
+
+```tsx
+// App.ts
+import MyComponent from "./MyComponent";
+
+function App() {
+ return (
+
+
+
+ );
+}
+```
+
+### Importing Solid and its utilities
+
+To use Solid, you must import the Solid library.
+The reactive primitives and utilities are exported from Solid's main module.
+
+```tsx
+import { createSignal } from "solid-js";
+```
+
+However, some of Solid's utilities are exported from their own modules.
+
+```tsx
+import { createStore } from "solid-js/store";
+```
+
+To see a full list of Solid's utilities, the Reference Tab in the sidebar provides the API Documentation.
+
+
+---
+title: Class and style
+order: 2
+---
+
+Similar to HTML, Solid uses `class` and `style` attributes to style elements via [CSS (Cascading Style Sheets)](https://developer.mozilla.org/en-US/docs/Glossary/CSS).
+
+- **Class attribute**: Enables styling one or more elements through CSS rules.
+- **Style attribute**: Inline styles that style single elements.
+
+## Inline styling
+
+The `style` attribute allows you to style a single element and define CSS variables dynamically during runtime.
+To use it, you can pass either a string or an object.
+
+```tsx
+// String
+
This is a red div
+
+// Object
+
This is a red div
+```
+
+When using an object, the keys represent the CSS property names, and the values represent the CSS property values.
+The keys must be in dash-case, and the values must be strings.
+
+
+
+While inline styles are useful for rapid prototyping, they are not recommended for production use.
+This is because they are not reusable, and they can be difficult to maintain over time.
+
+## Classes
+
+The `class` attribute allows you to style one or more elements through CSS rules.
+This provides a more structured approach to styling, as it allows you to reuse styles across multiple elements.
+
+Classes are defined in CSS files, which are then imported into the component files that use them.
+You can import these files using the `import` statement at the top of your component file.
+Once imported into a component, the classes are scoped to that component and any of its children.
+
+```jsx
+import "./Card.css";
+
+function Card() {
+ // ...
+}
+```
+
+### Dynamic styling
+
+Dynamic styling provides a way to change the appearance of a component based on state or other factors like user inputs.
+This is useful for creating components that can adapt to different scenarios without having to create multiple versions of the same component:
+
+```tsx
+const [theme, setTheme] = createSignal("light");
+
+
+ This div's theme is determined dynamically!
+
;
+```
+
+[Props](/concepts/components/props) are another way to change styles.
+By passing props to components, you can adapt styles based on the component's usage or the data it receives:
+
+```tsx
+function ThemedButton(props) {
+ return (
+
+ );
+}
+```
+
+### `classList`
+
+When you want to apply multiple classes to an element, you can use the [`classList` attribute](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList).
+To use it, you can pass either a string or an object where the keys represent the class names and the values represent a boolean expression.
+When the value is `true`, the class is applied; when `false`, it is removed.
+
+```tsx
+const [current, setCurrent] = createSignal("foo");
+
+;
+```
+
+`classList` is often more efficient than `class` when handling multiple conditional classes.
+This is because `classList` selectively toggles only the classes that require alteration, while `class` will be re-evaluated each time.
+For a single conditional class, using `class` might be simpler but as the number of conditional classes increases, `classList` offers a more readable and declarative approach.
+
+
+ While it is possible, mixing `class` and `classList` can introduce unexpected errors.
+ If both are reactive when the `class` value changes, Solid will set the entire `class` attribute.
+ This will remove any classes set by `classList`.
+
+ To avoid this, the `class` attribute should be set to a static string or nothing.
+ Alternatively, `class` can be set to a static computed value (e.g. `class={baseClass()}`), but then it must be put before any `classList` attributes.
+
+ Additionally, since `classList` is a pseudo-attribute, it doesn't work in prop spreads like `` or in ``.
+
+
+For a guide on how to style your components, see [Styling Your Components](/guides/styling-your-components), where we cover the different ways to style your components using libraries such as [TailwindCSS](https://tailwindcss.com/).
+
+
+---
+title: Event handlers
+order: 3
+---
+
+Event handlers are functions that are called in response to specific events occurring in the browser, such as when a user clicks or taps on an element.
+
+Solid provides two ways to add event listeners to the browser:
+
+- [`on:__`](/reference/jsx-attributes/on): adds an event listener to the `element`. This is also known as a _native event_.
+- [`on__`](/reference/jsx-attributes/on_): adds an event listener to the `document` and dispatches it to the `element`. This can be referred to as a _delegated event_.
+
+Delegated events flow through the [_component tree_](/concepts/components/basics#component-trees), and save some resources by performing better on commonly used events.
+Native events, however, flow through the _DOM tree_, and provide more control over the behavior of the event.
+
+## Using events
+
+To add an event handler, prefix the event name with either `on` or `on:`, and assign it to the function you wish to call when the event is dispatched.
+
+```tsx
+// delegated event
+
+
+// native event
+
... very long text ...
+```
+
+Delegated events are **not case sensitive**, therefore using delegated event handlers in Solid can be written using camelCase or all lowercase.
+Note that while delegated events can be written both ways, native events _are_ case sensitive.
+
+```tsx
+
+```
+
+For any other events, such as custom events or events you wish _not_ to be delegated, the `on:` attribute will add an event listener as-is.
+This is what makes the event listener case sensitive.
+
+```tsx
+
+```
+
+For typing standard or custom events using `on:`, the TypeScript page has a section about [event handlers](/configuration/typescript#event-handling).
+
+## Binding events
+
+To optimize event handlers, you can pass an array as the event handler, replacing the function.
+When doing this, the second item passed into the array is supplied as the handler's first argument:
+
+```tsx
+const handler = (data, event) => {
+ console.log("Data:", data, "Event:", event);
+};
+
+;
+```
+
+In this example, the `Hello!` string is passed as the `data` parameter in the `handler` function when the button is clicked.
+
+By binding events in this way, Solid avoids the overhead of using JavaScript's [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind) method and adding an additional closure.
+
+### Dynamic handlers
+
+An event handler does not form part of the reactive system.
+If you were to pass the handler as a signal, it will not respond to the changes of that signal.
+In other words, events do not dynamically update, and the bindings are not reactive.
+This is because attaching and detaching listeners is a resource-intensive task.
+
+Since event handlers are called like a standard function, you can design them to call a reactive source, if needed.
+
+In the following example, `handleClick` represents a prop that has the flexibility to adopt any function.
+As a result, there is no requirement for these functions to be reactive.
+
+```tsx
+
props.handleClick?.()} />
+```
+
+## Event delegation
+
+Instead of attaching event listeners to every individual element, Solid uses _synthetic event delegation_, through the [`on__`](/reference/jsx-attributes/on_) form .
+In this method event listeners are attached to the `document` element, and dispatch events to the relevant elements as they bubble up.
+
+By keeping the number of event listeners to a minimum, events can be captured more effectively.
+This is especially useful when working with a large number of elements, such as in a table or list.
+
+Supported events such as `click`, `input` and `keydown` are just a few examples that are optimized in this way.
+To view the full list see the [references below](#list-of-delegated-events).
+
+If you need to attach an event listener to an element that is not supported by Solid's event delegation, such as a custom event in a [custom element](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements), you can use the [`on:__`](/reference/jsx-attributes/on) form.
+
+```tsx
+
+```
+
+### Event delegation considerations
+
+While delegated events provide some performance enhancements, there are tradeoffs.
+
+Event delegation is designed for event propagation through the JSX Tree, rather than the DOM Tree.
+This can differ from the previous expectations of how events work and flow.
+
+Some things to keep in mind include:
+
+- Delegated event listeners are added _once_ per event type and handle all future events of that type.
+This means that delegated event listeners remain active even if the element that added them and its handler is removed.
+ For example, if a `div` listens for `mousemove` and is later removed, the `mousemove` events will still be dispatched to the `document` in case a different element is also listening for mouse moves.
+
+```tsx
+
+```
+
+
+
+Rather than using delegated events for events that happen infrequently, **native events** are a better solution.
+Since these events happen in specific circumstances, they do not benefit from the performance improvements you get with event delegation.
+
+```tsx
+
+```
+
+
+
+- `event.stopPropagation()` does not work as expected since events are attached to the `document` rather than the `element`.
+
+ With cases like this, a native event is recommended.
+ As an example, using a native event would stop the following event from reaching the `div native` handler, which is _not_ the case for delegated events.
+ You can [view this example in the Solid Playground](https://playground.solidjs.com/anonymous/c5346f84-01e4-4080-8ace-4443ffd0bb10).
+
+```tsx
+onMount(() => {
+ ref.addEventListener("click", () => {
+ console.log("div native");
+ });
+});
+
+
+
;
+```
+
+```shellsession title="Console output"
+// Button clicked
+div native
+button
+```
+
+You can solve this by switching the `button` event to using a native event:
+
+```tsx ins="on:click"
+// ...
+
+// ...
+```
+
+```shellsession title="Console output"
+// Button clicked
+button
+```
+
+[See how this solution differs in the Solid Playground](https://playground.solidjs.com/anonymous/9e2deddc-2e83-4ac2-8ee0-49c7c3a45d11).
+
+- Portals propagate events following the _component tree_ and not the _DOM tree_, making them easier to use.
+ This means when a `Portal` gets attached to the `body`, any events will propagate up to the `container`.
+
+```tsx
+
+```
+
+
+
+ `onChange` and `onInput` events work according to their native behavior:
+ - `onInput` will fire immediately after the value has changed
+ - In `` fields, `onChange` will only fire after the field loses focus.
+
+
+
+### List of delegated events
+
+You can also view this list in our [source code](https://github.com/ryansolid/dom-expressions/blob/main/packages/dom-expressions/src/constants.js) (see `DelegatedEvents`).
+
+- [`beforeinput`](https://developer.mozilla.org/en-US/docs/Web/API/Element/beforeinput_event)
+- [`click`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click)
+- [`dblclick`](https://developer.mozilla.org/en-US/docs/Web/API/Element/dblclick_event)
+- [`contextmenu`](https://developer.mozilla.org/en-US/docs/Web/API/Element/contextmenu_event)
+- [`focusin`](https://developer.mozilla.org/en-US/docs/Web/API/Element/focusin_event)
+- [`focusout`](https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event)
+- [`input`](https://developer.mozilla.org/en-US/docs/Web/API/Element/input_event)
+- [`keydown`](https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event)
+- [`keyup`](https://developer.mozilla.org/en-US/docs/Web/API/Element/keyup_event)
+- [`mousedown`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousedown_event)
+- [`mousemove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mousemove_event)
+- [`mouseout`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseout_event)
+- [`mouseover`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseover_event)
+- [`mouseup`](https://developer.mozilla.org/en-US/docs/Web/API/Element/mouseup_event)
+- [`pointerdown`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerdown_event)
+- [`pointermove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointermove_event)
+- [`pointerout`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerout_event)
+- [`pointerover`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerover_event)
+- [`pointerup`](https://developer.mozilla.org/en-US/docs/Web/API/Element/pointerup_event)
+- [`touchend`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchend_event)
+- [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchmove_event)
+- [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/API/Element/touchstart_event)
+
+
+---
+title: Props
+---
+
+Props are a way to pass state from a parent component to a child component.
+These read-only properties are passed to components as attributes within JSX and are accessible within the component via the `props` object:
+
+```tsx
+function App() {
+ // Passing a prop named "name" to the MyComponent component
+ return (
+
+
+
+ );
+}
+```
+
+To access the props in the child component, you use the `props` object:
+
+```tsx
+function MyComponent(props) {
+ return
Hello {props.name}
;
+}
+```
+
+## `mergeProps`
+
+[`mergeProps`](/reference/reactive-utilities/merge-props) is a Solid utility function designed to merge multiple potentially reactive objects together.
+It behaves similar to [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) but will retain the reactivity of the properties being merged.
+This helps ensure that when individual properties within the merged object change, their reactivity is not lost.
+
+```typescript
+import { mergeProps } from "solid-js";
+
+function MyComponent(props) {
+ // Using mergeProps to set default values for props
+ const finalProps = mergeProps({ defaultName: "Ryan Carniato" }, props);
+
+ return
Hello {finalProps.defaultName}
;
+}
+
+// Usage:
+```
+
+When merging props, if there is no existing value for a property, the value from the first object will be used.
+However, if a value already exists, it will be used instead, all while retaining the reactivity of the property.
+
+## Destructuring props
+
+Props are read-only so that child components do not directly modify the data passed by the parent.
+This also encourages one-way data flow, a pattern often seen to promote more predictable data management.
+
+With Solid, destructuring props is not recommended as it can break reactivity.
+Instead, you should access props directly from the `props` object, or wrap them in a function to ensure they are always up-to-date:
+
+```typescript
+function MyComponent(props) {
+ const { name } = props; // ❌: breaks reactivity and will not update when the prop value changes
+ const name = props.name; // ❌: another example of breaking reactivity
+ const name = () => props.name; // ✓: by wrapping `props.name` into a function, `name()` always retrieves its current value
+}
+```
+
+### `splitProps`
+
+[`splitProps`](/reference/reactive-utilities/split-props) is a utility function designed to help split a single props object into multiple sets of props, retaining the reactivity of the individual properties.
+It provides a way to destructure props without breaking reactivity.
+
+`splitProps` gives you the ability to define one or more arrays of keys that you wish to extract into separate props objects, all while retaining the reactivity of the individual properties.
+It will return an array of props objects related to each set of keys, plus an additional props object containing any remaining keys.
+
+When passing props to child components, you can use `splitProps` to split the props into multiple groups, and then pass each group to the appropriate child component:
+
+```typescript
+import { splitProps } from "solid-js";
+
+function ParentComponent(props) {
+ // Splitting props into two groups: 'name' and 'age'
+ const [greetingProps, personalInfoProps, restProps] = splitProps(
+ props,
+ ["name"],
+ ["age"]
+ );
+
+ // Using greetingProps and personalInfoProps in the current component
+ return (
+
+
+
+ {/* restProps can be passed down or used as needed */}
+
+ );
+}
+```
+
+## Passing props to children
+
+In most instances, simply using `props` within JSX will work without any issues.
+However, there are some cases where accessing `props.children` multiple times can introduce problems and unexpected behaviours, such as repeated creation of child components or elements.
+For instances like these, Solid provides a [`children`](/reference/component-apis/children) helper that ensures you always get the right child components without anything unwanted happening.
+
+```typescript
+import { children } from "solid-js";
+
+function ColoredList(props) {
+ const safeChildren = children(() => props.children);
+
+ return <>{safeChildren()}>;
+}
+```
+
+## Prop drilling
+
+Prop drilling is a term used to describe the process of passing props through multiple layers of components.
+While it can be a useful pattern, it can also lead to problems.
+When components are nested deeply, passing props through each component can become difficult to manage.
+Additionally, this can lead to components receiving props that they do not need, unnecessary re-renders, and trouble refactoring.
+
+Since components in Solid do not own state, props are not needed to pass state between components, but may be used.
+Because of this, there may be times when you need to pass props through multiple layers of components.
+A common solution to this problem is to use [Context](/concepts/context) to pass state to deeply nested components without having to pass props through each component in between.
+
+
+---
+title: "Context"
+order: 5
+---
+
+Context provides a way to pass data through the component tree without having to pass props down manually at every level.
+
+## When to use context
+
+When you have a large [component tree](/concepts/components/basics#component-trees) that requires state to be shared, context can be used.
+Context can be employed to avoid [prop drilling](/concepts/components/props#prop-drilling), which is the practice of passing props through intermediate elements without using them directly.
+
+If you want to avoid passing some props through a few layers, when applicable, adjusting your component hierarchy may be an easier solution.
+[Signals](/concepts/signals) are often the simplest solution since they can be imported directly into the components that need them.
+
+Context, however, is designed to share data that is global to an application or for information that is regularly accessed by multiple components in an application's component tree.
+This offers a way to access state across an application without passing props through intermediate layers or importing them directly into components.
+
+## Creating context
+
+Context is created using the [`createContext`](/reference/component-apis/create-context) function.
+This function has a `Provider` property that wraps the component tree you want to provide context to.
+
+
+
+
+
+## Providing context to children
+
+To pass a value to the `Provider`, you use the `value` prop which can take in any value, including [signals](#updating-context-values).
+Once a value is passed to the `Provider`, it is available to all components that are descendants of the `Provider`.
+
+When passing a single value, it can be directly passed to the `value` prop:
+
+```jsx title="/context/component.jsx"
+import { createContext, useContext } from "solid-js";
+import { MyContext } from "./create";
+
+const Provider = (props) => (
+ {props.children}
+);
+```
+
+
+When passing multiple values (as an `array` or `object`), it is recommended to use a [store](/reference/component-apis/create-context#usage).
+
+
+## Consuming context
+
+Once the values are available to all the components in the context's component tree, they can be accessed using the [`useContext`](/reference/component-apis/use-context) utility.
+This utility takes in the context object and returns the value(s) passed to the `Provider`:
+
+```jsx title="/context/component.jsx"
+import { createContext, useContext } from "solid-js";
+import { MyContext } from "./create";
+
+const Provider = (props) => (
+
+ {props.children}
+
+);
+
+const Child = () => {
+ const value = useContext(MyContext);
+
+ return (
+
+ {value}
+
+ );
+};
+
+export const App = () => (
+
+
+
+);
+```
+
+## Customizing Context Utilities
+
+When an application contains multiple context objects, it can be difficult to keep track of which context object is being used.
+To solve this issue, you can create a custom utilities to create a more readable way to access the context values.
+
+For example, when wrapping a component tree, you may want to create a custom `Provider` component that can be used to wrap the component tree.
+This also provides you with the option of re-using the `Provider` component in other parts of your application, if needed.
+
+```jsx
+import { createSignal, createContext, useContext } from "solid-js";
+import { CounterContext } from "~/context/counter";
+
+export function CounterProvider(props) {
+ return (
+
+ {props.children}
+
+ );
+}
+```
+
+Now if you had to access the Provider in different areas of your application, you can simply import the `CounterProvider` component and wrap the component tree:
+
+```jsx
+import { CounterProvider } from "./counterProvider";
+
+export function App() {
+ return (
+
+
Welcome to Counter
+
+
+ );
+}
+```
+
+Similarly, you can create a custom utility to access the context values.
+Instead of importing `useContext` and passing in the context object on each component that you're using it in, creating a customized utility can make it easier to access the values you need:
+
+```jsx
+export function useCounter() {
+ return useContext(CounterContext);
+}
+```
+
+The `useCounter()` utility in this example can now be imported into any component that needs to access the context values:
+
+```jsx
+import { useCounter } from "./counter";
+
+export function CounterProvider(props) {
+ const count = useCounter();
+ return (
+ <>
+
{count()}
+ >
+ );
+}
+```
+
+## Updating Context Values
+
+[Signals](/concepts/signals) offer a way to synchronize and manage data shared across your components using context.
+You can pass a signal directly to the `value` prop of the `Provider` component, and any changes to the signal will be reflected in all components that consume the context.
+
+
+
+```jsx
+import { CounterProvider } from "./Context";
+import { Child } from "./Child";
+
+export function App() {
+ return (
+
+
+
+
+This offers a way to manage state across your components without having to pass props through intermediate elements.
+
+## Debugging with context
+
+`createContext` takes in an _optional_ default value and it is possible it can return `undefined` if not provided.
+When working with TypeScript, this can introduce type issues that make it difficult to determine why your component is not rendering as expected.
+
+To solve this issue, a default value can be specified when creating a context object, or errors can be handled manually through the use of a custom `useMyContext` utility:
+
+```tsx title="/context/counter-component.tsx"
+import { useContext } from "solid-js";
+
+function useMyContext() {
+ const value = useContext(MyContext);
+
+ if (!value) {
+ throw new Error("Missing context Provider");
+ }
+
+ return value;
+}
+
+function Child() {
+ const value = useMyContext();
+
+ return
{value}
;
+}
+```
+
+## Common issues with `createContext` and `useContext`
+
+If no default value is passed to `createContext`, it is possible for `useContext` to return `undefined`.
+
+
+Read more about default values in the [`createContext`](/reference/component-apis/create-context) entry.
+
+
+Because of this, if an initial value was not passed to `createContext`, the TS type signature of `useContext` will indicate that
+the value returned might be `undefined` (as mentioned above).
+This can be quite annoying when you want to use the context inside a component, and particularly when immediately destructuring the context.
+Additionally, if you use `useContext` and it returns `undefined` (which is often, but not always, the result of a bug), the error message thrown at runtime can be confusing.
+
+The most common solution for it is to wrap all uses of `useContext` in a function that will explicitly throw a helpful error if the context is `undefined`.
+This also serves to narrow the type returned, so TS doesn't complain.
+As an example:
+
+```ts title="/context/counter-component.tsx"
+function useCounterContext() {
+ const context = useContext(CounterContext)
+ if (!context) {
+ throw new Error("can't find CounterContext")
+ }
+ return context
+}
+```
+
+
+
+---
+title: "Conditional rendering"
+order: 1
+---
+
+Conditional rendering is the process of displaying different UI elements based on certain conditions.
+This is a common pattern in UI development, and is often used to show or hide elements based on user input, data, or other conditions.
+
+Solid offers dedicated components to handle conditional rendering in a more straightforward and readable way.
+
+## Show
+
+`` renders its children when a condition is evaluated to be true.
+Similar to the [ternary operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator) in JavaScript, it uses control logic flow within JSX to determine what to render.
+
+`` has a `when` property that is used to determine whether or not to render its children.
+When there is a change in the state or props it depends on, this property is re-evaluated.
+This property can be a boolean value, or a function that returns a boolean value.
+
+```jsx
+import { Show } from "solid-js"
+
+
+
Loading...
+
+```
+
+`` has the `fallback` property that can be used to specify the content to be rendered when the condition evaluates to false.
+This property can return a JSX element.
+
+```jsx
+import { Show } from "solid-js"
+
+Loading...
}>
+
Hi, I am {data().name}.
+
+```
+
+If there are multiple conditions that need to be handled, `` can be nested to handle each condition.
+
+```jsx
+import { Show } from "solid-js"
+
+
+
Loading...
+
+
Error: {data.error}
+
+
+```
+
+
+## Switch and Match
+
+When there are multiple conditions that need to be handled, it can be difficult to manage the logic flow with nested `` components.
+Solid has the `` and `` components for this purpose.
+
+Similar to JavaScript's [switch/case](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) structure, `` wraps multiple `` components so that each condition is evaluated _in sequence_.
+The first `` component that evaluates to true will have its children rendered, and the rest will be ignored.
+
+```jsx
+import { Switch, Match } from "solid-js"
+
+
+
+
Outcome 1
+
+
+
Outcome 2
+
+
+```
+
+Similar to ``, each `` component has a `when` property that is used to determine whether or not to render its children.
+An optional `fallback` property can also be passed to `` to specify the content be rendered when none of the `` components evaluate to true.
+
+```jsx
+import { Switch, Match } from "solid-js"
+
+Fallback content}>
+
+
Outcome 1
+
+
+
Outcome 2
+
+
+```
+
+
+---
+title: "Dynamic"
+order: 2
+---
+
+`` is a Solid component that allows you to render components dynamically based on data.
+By passing either a string representing a [native HTML element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element) or a component function to the `component` prop, you can render the chosen component with the remaining props you provide.
+
+```jsx
+import { createSignal, For } from "solid-js"
+import { Dynamic } from "solid-js/web"
+
+const RedDiv = () =>
Red
+const GreenDiv = () =>
Green
+const BlueDiv = () =>
Blue
+
+const options = {
+ red: RedDiv,
+ green: GreenDiv,
+ blue: BlueDiv,
+}
+
+function App() {
+ const [selected, setSelected] = createSignal("red")
+
+ return (
+ <>
+
+
+ >
+ )
+}
+```
+
+This example renders a `
+ >
+ )
+}
+```
+
+Instead of a more verbose [`` and ``](/concepts/control-flow/conditional-rendering) statement, `` offers a more concise way to render components dynamically.
+
+## Props
+
+When working with these components, you can pass [props](/concepts/components/props) to the component you are rendering by passing them to the `` component.
+This makes them available to the component you are rendering, similar to how you would pass props to components in JSX.
+
+```jsx
+import { Dynamic } from "solid-js/web"
+
+function App() {
+ return (
+
+ )
+}
+```
+
+
+---
+title: "Error boundary"
+order: 5
+---
+
+`` is a component that can be used to catch errors thrown by child components.
+When encountering an error, this component will render a fallback UI instead of the problematic child component(s).
+
+```jsx
+import { ErrorBoundary } from "solid-js";
+
+
Error: {err.message}
}>
+
+
+```
+
+`` accepts a `fallback` prop that can be used to render a custom error message, or to provide a friendly notification to the user.
+This prop accepts a function that receives the caught error as an argument, providing a flexible way to handle different error scenarios.
+
+
+
+By wrapping parts of your application in ``, you can prevent the entire application from crashing when an error occurs due to a single component.
+
+When an error is encountered, the `` component will catch the error and render the fallback UI instead of the problematic component(s).
+This way, even when a component fails, the user has a controlled UI response instead of a broken interface.
+
+
+---
+title: "List rendering"
+order: 3
+---
+
+List rendering allows you to generate multiple elements from a collection of data, such as an array or object, where each element corresponds to an item in the collection.
+
+When dealing with dynamic data, Solid offers two ways to render lists: the `` and `` components.
+Both of these components help you loop over data collections to generate elements, however, they both cater to different scenarios.
+
+## ``
+
+`` is a looping component that allows you to render elements based on the contents of an array or object.
+This component is designed to be used with **complex data structures**, such as arrays of objects, where the order and length of the list may change frequently.
+
+The sole property in `` is `each` , through which you can specify the data collection to loop over.
+This property expects an array, however, it can also accept objects that have been converted to arrays using utilities such as [`Object.entries`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) or [`Object.values`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values).
+
+```jsx
+import { For } from "solid-js"
+
+
+ {(item, index) =>
+ // rendering logic for each element
+ }
+
+```
+
+Between the `` tags, the component requires a [callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) which will dictate how each item in the data collection should be rendered.
+This structure resembles the callback used within JavaScript's [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) method, providing a familiar pattern to follow.
+
+The function receives two arguments:
+- `item`: represents the current item in the data collection that is being rendered over.
+- `index`: the current item's index within the collection.
+
+You can access the current `item` and `index` to dynamically set attributes or content of the JSX elements.
+Index is a [*signal*](/concepts/signals) and must be called as a function to retrieve its value.
+
+```jsx
+
+ {(item, index) => (
+
+ {item.name}
+
+ )}
+
+```
+
+## `Index`
+
+``, similar to ``, is a looping component that allows you to render elements based on the contents of an array or object.
+However, when the order and length of the list remain _stable_, but the content may change frequently, `` is a better option because it results in fewer re-renders.
+
+```jsx
+import { Index } from "solid-js"
+
+
+ {(item, index) => (
+ // rendering logic for each element
+ )}
+
+```
+
+Similar to the `` component, `` accepts a single property named `each`, which is where you pass the structure you wish to loop over.
+
+Where the `index` is a signal with ``, it remains fixed with ``.
+This is because `` is more concerned with the **index** of the elements in the array.
+Because of this, the `item` is a signal, allowing the _content_ at each index to change without a re-render while the index remains fixed.
+
+```jsx
+import { Index } from "solid-js"
+
+
+ {(item, index) => (
+
+ {item().name} - {item().completed}
+
+ )}
+
+```
+
+## `` vs ``
+
+`` is designed to be used when the *order* and *length* of the list may change frequently.
+When the list value changes in ``, the entire list is re-rendered.
+However, if the array undergoes a change, such as an element shifting position, `` will manage this by simply **moving** the corresponding DOM node and **updating** the index.
+
+``, however, is designed to be used when the **order** and **length** of the list remain _stable_, but the content may change frequently.
+When the list value changes in ``, only the content at the specified index is updated.
+
+### When to use ``
+
+In cases where signals, nested loops, or dynamic lists are not required, `` is the best option.
+For example, when creating a list of static elements, such as a list of links, `` is the best option to use.
+This is because it will only modify the indexes of the elements in the list, rather than re-rendering the entire list.
+
+```jsx
+import { createSignal, For } from "solid-js"
+
+function StringList() {
+ const [items, setItems] = createSignal(["Item 1", "Item 2", "Item 3"])
+
+ return (
+
+ {
+ // add the new item to the list
+ }}
+ />
+
+ {(item, index) => (
+
+ {item} - {index()}
+
+ )}
+
+
+ )
+}
+```
+
+If you are working with signals, [JavaScript primitives like strings and numbers](https://developer.mozilla.org/en-US/docs/Glossary/Primitive) or input fields, `` is the better option to use.
+If you were using ``, the entire list would be re-rendered when a value changes, even if the length of the list remains unchanged.
+``, instead, will update the content at the specified index, while the rest of the list remains unchanged.
+
+```jsx
+import { createSignal, Index } from "solid-js"
+
+function FormList() {
+ const [inputs, setInputs] = createSignal(['input1','input2','input3'])
+ return(
+
+ )
+}
+```
+
+---
+title: "Portal"
+order: 3
+---
+
+When an element requires rendering outside of the usual document flow, challenges related to stacking contents and z-index can interfere with the desired intention or look of an application.
+`` helps with this by putting elements in a different place in the document, bringing an element into the document flow so they can render as expected.
+
+```jsx
+import { Portal } from "solid-js/web"
+
+
+
...
+
+```
+
+The content nested within `` is rendered and positioned by default at the end of the document body.
+
+
+
+This can be changed by passing a `mount` prop to ``.
+The `mount` prop accepts a [DOM node](https://developer.mozilla.org/en-US/docs/Web/API/Node), which will be used as the mount point for the portal content.
+
+```jsx
+import { Portal } from "solid-js/web"
+
+
+
...
+
+```
+
+
+Using `` can be particularly useful in cases where elements, like information popups, might be clipped or obscured due to the overflow settings of their parent elements.
+By putting the element outside of the parent element, it is no longer bound by the overflow settings of its parent.
+This creates a more accessible experience for users, as the content is no longer obscured.
+
+
+
+ `` will render wrapped unless specifically targeting `document.head`.
+
+ This is so events propagate through the Portal according to the component hierarchy instead of the elements hierarchy.
+
+By default, children will wrap in a `
`. If you portal into an SVG, then the `isSVG` prop must be used to avoid wrapping the children in a `
` and wrap in a `` instead.
+
+```jsx
+import { Portal } from "solid-js/web"
+
+function Rect() {
+ return (
+
+
+
+ );
+}
+
+function SVG() {
+ return ;
+}
+```
+
+
+
+---
+title: Derived signals
+order: 1
+---
+
+Derived signals are functions that rely on one or more [signals](/concepts/signals) to produce a value.
+
+These functions are not executed immediately, but instead are only called when the values they rely on are changed.
+When the underlying signal is changed, the function will be called again to produce a new value.
+
+```js
+const double = () => count() * 2;
+```
+
+In the above example, the `double` function relies on the `count` signal to produce a value.
+When the `count` signal is changed, the `double` function will be called again to produce a new value.
+
+Similarly you can create a derived signal that relies on a store value because stores use signals under the hood.
+To learn more about how stores work, [you can visit the stores section](/concepts/stores).
+
+```js
+const fullName = () => store.firstName + ' ' + store.lastName;
+```
+
+These dependent functions gain reactivity from the signal they access, ensuring that changes in the underlying data propagate throughout your application.
+It is important to note that these functions do not store a value themselves; instead, they can update any effects or components that depend on them.
+If included within a component's body, these derived signals will trigger an update when necessary.
+
+While you can create derived values in this manner, Solid created the [`createMemo`](/reference/basic-reactivity/create-memo) primitive.
+To dive deeper into how memos work, [check out the memos section](/concepts/derived-values/memos).
+
+
+---
+title: Memos
+order: 2
+---
+
+Memos are a type of reactive value that can be used to memoize derived state or expensive computations.
+They are similar to [derived signals](/concepts/derived-values/derived-signals) in that they are reactive values that automatically re-evaluate when their dependencies change.
+However, unlike derived signals, memos are optimized to execute only once for each change in their dependencies.
+
+Memos expose a _read-only_ reactive value (like a [signal](/concepts/signals)) and track changes in their dependencies (similar to an [effect](/concepts/effects)).
+This makes them useful for caching the results of expensive or frequently accessed computations.
+By doing this, memos minimize unnecessary work within an application by retaining the results of a computation until its dependencies change.
+
+## Using memos
+
+A memo is created using the `createMemo` function.
+Within this function, you can define the derived value or computations you wish to memoize.
+When called, `createMemo` will return a **getter** function that reads the current value of the memo:
+
+```jsx
+import { createMemo, createSignal } from "solid-js"
+
+const [count, setCount] = createSignal(0)
+
+const isEven = createMemo(() => count() % 2 === 0)
+
+console.log(isEven()) // true
+
+setCount(3)
+console.log(isEven()) // false
+```
+
+While memos look similar to effects, they are different in that they _return a value_.
+This value is the result of the computation or derived state that you wish to memoize.
+
+### Advantages of using memos
+
+While you can use a [derived signal](/concepts/derived-values/derived-signals) to achieve similar results, memos offer distinct advantages:
+
+- Memos are optimized to execute only once for each change in their dependencies.
+- When working with expensive computations, memos can be used to cache the results so they are not recomputed unnecessarily.
+- A memo will only recompute when its dependencies change, and will not trigger subsequent updates (as determined by [`===` or strict equality](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)) if its dependencies change but its value remains the same.
+- Any signal or memo accessed within a memo's function is **tracked**.
+ This means that the memo will re-evaluate automatically when these dependencies change.
+
+
+
+## Memo vs. effect
+
+Both memos and effects are important when managing reactive computations and side effects.
+They, however, serve different purposes and each has their own unique behaviors.
+
+| | Memos | Effects |
+| -------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
+| Return value | Yes - returns a getter for the result of the computation or derived state. | Does not return a value but executes a block of code in response to changes. |
+| Caches results | Yes | No |
+| Behavior | Function argument should be pure without reactive side effects. | Function argument can cause side effects like UI updates or data fetches. |
+| Dependency tracking. | Yes | Yes |
+| Example use cases | Transforming data structures, computing aggregated values, derived state, or other expensive computations. | UI updates, network requests, or external integrations. |
+
+## Best practices
+
+### Pure functions
+
+When working with memos, it is recommended that you leave them "pure".
+
+```jsx
+import { createSignal, createMemo } from "solid-js"
+
+const [count, setCount] = createSignal(0)
+const isEven = createMemo(() => count() % 2 === 0) // example of a pure function
+```
+
+A pure function is one that does not cause any side effects.
+This means that the function's output should solely depend on its inputs.
+
+When you introduce side effects into a memo, it can complicate the reactivity chain.
+This can lead to unexpected behavior, such as infinite loops, that lead your application to crash.
+
+```jsx
+import { createSignal, createMemo } from "solid-js"
+
+const [count, setCount] = createSignal(0)
+const [message, setMessage] = createSignal("")
+
+const badMemo = createMemo(() => {
+ if (count() > 10) {
+ setMessage("Count is too high!") // side effect
+ }
+ return count() % 2 === 0
+})
+```
+
+These infinite loops can be triggered when a memo has a side effect that causes its dependencies to change.
+This will cause the memo to re-evaluate, which will then trigger the side effect again, and so on until the application crashes.
+
+This can be avoided by using a [`createEffect`](/reference/basic-reactivity/create-effect) to handle the side effects instead:
+
+```jsx
+import { createSignal, createMemo, createEffect } from "solid-js"
+
+const [count, setCount] = createSignal(0)
+const [message, setMessage] = createSignal("")
+
+const isEven = createMemo(() => count() % 2 === 0)
+
+createEffect(() => {
+ if (count() > 10) {
+ setMessage("Count is too high!")
+ }
+})
+```
+
+Here, the `createEffect` will handle the side effects, while the `isEven` memo will remain pure.
+
+### Keep logic in memos
+
+Memos are optimized to execute only once for each change in their dependencies.
+This means that you can remove unnecessary effects that are triggered by a memo's dependencies.
+
+When working with derived state, memos are the recommended approach over effects.
+Keeping the logic in a memo prevents unnecessary re-renders that can occur when using an effect.
+Similarly, effects are better suited to handle side effects, such as DOM updates, rather than derived state.
+This separation of concerns can help keep your code clean and easy to understand.
+
+```jsx
+// effect - runs whenever `count` changes
+createEffect(() => {
+ if (count() > 10) {
+ setMessage("Count is too high!")
+ } else {
+ setMessage("")
+ }
+})
+
+// memo - only runs when `count` changes to or from a value greater than 10
+const message = createMemo(() => {
+ if (count() > 10) {
+ return "Count is too high!"
+ } else {
+ return ""
+ }
+})
+```
+
+
+---
+title: Effects
+order: 4
+---
+
+Effects are functions that are triggered when the signals they depend on change.
+They play a crucial role in managing side effects, which are actions that occur outside of the application's scope, such as DOM manipulations, data fetching, and subscriptions.
+
+## Using an effect
+
+An effect is created using the `createEffect` function.
+This function takes a callback as its argument that runs when the effect is triggered.
+
+```jsx
+import { createEffect } from "solid-js";
+
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log(count());
+});
+```
+
+In this example, an effect is created that logs the current value of `count` to the console.
+When the value of `count` changes, the effect is triggered, causing it to run again and log the new value of `count`.
+
+## Managing dependencies
+
+Effects can be set to observe any number of dependencies.
+Dependencies are what allow an effect to track changes and respond accordingly.
+These can include signals, variables, props, context, or any other reactive values.
+When any of these change, the effect is notified and will run again to update its state.
+
+Upon initialization, an effect will run _once_, regardless of whether it has any dependencies.
+This is useful for setting up the effect and initializing variables or subscribing to [signals](/concepts/signals).
+After this run, the effect will only be triggered when any of its _dependencies_ change.
+
+```jsx
+createEffect(() => {
+ console.log("hello"); // will run only once
+});
+
+createEffect(() => {
+ console.log(count()); // will run every time count changes
+});
+```
+
+Solid automatically tracks the dependencies of an effect, so you do not need to manually specify them.
+This improves the tracking and minimizes the chances of overlooking or incorrectly identifying dependencies.
+
+## Subscribing to signals
+
+When an effect is set to observe a signal, it creates a subscription to it.
+This subscription allows the effect to track the changes in the signal's value, which causes it to observe any changes that may happen and to execute its callback accordingly.
+
+```jsx
+import { createSignal, createEffect } from "solid-js";
+
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log(count()); // Logs current value of count whenever it changes
+});
+```
+
+### Managing multiple signals
+
+Effects have the ability to observe multiple signals.
+A single effect can subscribe to multiple signals, and similarly, multiple effects can keep track of a single signal.
+This is useful when you need to update the UI based on multiple signals.
+
+When multiple signals are observed within a single effect, it will execute its callback whenever _any_ of the signals change.
+The effect will run even if only one of the signals changes, not necessarily all of them.
+This means that the effect will run with the latest values of all of the signals that it is observing.
+
+```jsx
+import { createSignal, createEffect } from "solid-js";
+
+const [count, setCount] = createSignal(0);
+const [message, setMessage] = createSignal("Hello");
+
+createEffect(() => {
+ console.log(count(), message());
+});
+
+setCount(1); // Output: 1, "Hello"
+setMessage("World"); // Output: 1, "World"
+```
+
+
+When a signal updates, it notifies all of its subscribers sequentially but the *order can vary*.
+While effects are guaranteed to run when a signal updates, the execution might **not** be instantaneous.
+This means that the order of execution of effects is *not guaranteed* and should not be relied upon.
+
+
+### Nested effects
+
+When working with effects, it is possible to nest them within each other.
+This allows each effect to independently track its own dependencies, without affecting the effect that it is nested within.
+
+```jsx
+createEffect(() => {
+ console.log("Outer effect starts");
+ createEffect(() => console.log("Inner effect"));
+ console.log("Outer effect ends");
+});
+```
+
+The order of execution is important to note.
+An inner effect will _not_ affect the outer effect.
+Signals that are accessed within an inner effect, will _not_ be registered as dependencies for the outer effect.
+When the signal located within the inner effect changes, it will trigger only the _inner effect_ to re-run, not the outer one.
+
+```jsx
+import { createSignal, createEffect } from "solid-js";
+
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log("Outer effect starts");
+ createEffect(() => console.log(count())); // when count changes, only this effect will run
+ console.log("Outer effect ends");
+});
+```
+
+This forces each effect to be independent of each other, which helps to avoid unexpected behaviour.
+Additionally, it allows you to create effects that are only triggered when certain conditions are met.
+
+## Lifecycle functions
+
+Effects have a lifecycle that can be managed using certain functions.
+These functions allow you to control the initialization and disposal of effects to build the type of behaviour that you need.
+This can include running a side effect only once, or cleaning up a task when it is no longer needed.
+
+### `onMount`
+
+In situations where you just want to run a side effect **once**, you can use the [`onMount`](/reference/lifecycle/on-mount) function.
+This lifecycle function is similar to an effect, but it does not track any dependencies.
+Rather, once the component has been initialized, the `onMount` callback will be executed and will not run again.
+
+```jsx
+import { onMount } from "solid-js";
+
+function Component() {
+ const [data, setData] = createSignal(null);
+
+ createEffect(() => {
+ data(); // will run every time data changes
+ });
+
+ onMount(async () => {
+ // will run only once, when the component is mounted
+ const fetchedData = await fetch("https://example.com/data");
+ setData(fetchedData);
+ });
+
+ return
...
;
+}
+```
+
+`onMount` provides the assurance that the callback will only run once.
+If using an effect in this situation, there is no guarantee that it will only run once, which can lead to unexpected behaviour.
+This makes `onMount` useful for API calls and other side effects that only need to be run once per component instance.
+
+### `onCleanup`
+
+While `onMount` is useful for running a side effect once, [`onCleanup`](/reference/lifecycle/on-cleanup) is helpful for cleaning up a task when it is no longer needed.
+`onCleanup` will run whenever the component unmounts, removing any subscriptions that the effect has.
+
+```jsx
+import { onCleanup } from "solid-js";
+
+function App() {
+ const [count, setCount] = createSignal(0);
+
+ const timer = setInterval(() => {
+ setCount((prev) => prev + 1);
+ }, 1000);
+
+ onCleanup(() => {
+ clearInterval(timer);
+ });
+
+ return
Count: {count()}
;
+}
+```
+
+In this example, the `onCleanup` function is used to clear the interval that is set up in the effect.
+To avoid the interval from running indefinitely, the `onCleanup` function is used to clear the interval once the component unmounts.
+
+`onCleanup` can be used to avoid memory leaks.
+These occur when a component is unmounted, but references to it still exist and, as a result, could still be running in the background.
+Using `onCleanup` to remove any subscriptions or references to the component can help to avoid this issue.
+
+
+---
+title: "Intro to reactivity"
+order: 1
+---
+
+**Note**: While this guide is useful for understanding reactive systems, it does use some Solid-specific terminology.
+
+Reactivity powers the interactivity in Solid applications.
+This programming paradigm refers to a system's ability to respond to changes in data or state automatically.
+With Solid, reactivity is the basis of its design, ensuring application's stay up-to-date with its underlying data.
+
+## Importance of reactivity
+
+1. Reactivity keeps the user interface (UI) and state in sync, which reduces the need for manual updates.
+
+2. Real-time updates create a more responsive and interactive user experience.
+
+```jsx
+function Counter() {
+ const [count, setCount] = createSignal(0);
+ const increment = () => setCount((prev) => prev + 1);
+
+ return (
+
+ Count: {count()}{" "}
+ {/* Only `count()` is updated when the button is clicked. */}
+
+
+ );
+}
+```
+
+This `Counter` function sets up a button that, when clicked, calls the `increment` function to increase the `count` by one.
+This updates just the number displayed _without_ refreshing the entire component.
+
+
+
+## Reactive principles
+
+### Signals
+
+Signals serve as core elements in reactive systems, playing an important role in data management and system responsiveness.
+They are responsible for storing and managing data, as well as triggering updates across the system.
+This is done through the use of getters and setters.
+
+```jsx
+const [count, setCount] = createSignal(0);
+// ^ getter ^ setter
+```
+
+
+
+- **Getter**: A function responsible for accessing the current value of the signal.
+ You call a getter to access the data stored in a signal within a component.
+
+- **Setter**:
+ The function used to modify a signal's value.
+ To trigger reactive updates across an application, you call a setter to update the value of a signal.
+
+```js
+console.log(count()); // `count()` is a getter that returns the current value of `count`, which is `0`.
+
+setCount(1); // the setter, `setCount`, updates the value of `count`.
+
+console.log(count()); // the updated value of `count` is now `1`.
+```
+
+### Subscribers
+
+Subscribers are the other core element in reactive systems.
+They are responsible for tracking changes in signals and updating the system accordingly.
+They are automated responders that keep the system up-to-date with the latest data changes.
+
+Subscribers work based on two main actions:
+
+- **Observation**: At their core, subscribers observe signals.
+ This keeps the subscriber primed to pick up on any changes to the signal they are tracking.
+- **Response**: When a signal changes, the subscriber is notified.
+ This triggers the subscriber to respond to the change in the signal.
+ This can involve tasks like updating the UI or calling external functions.
+
+```jsx
+function Counter() {
+ const [count, setCount] = createSignal(0);
+ const increment = () => setCount((prev) => prev + 1);
+
+ createEffect(() => {
+ console.log(count());
+ });
+ // the `createEffect` will trigger the console log every time `count` changes.
+}
+```
+
+## State management
+
+State management is the process of managing the state of an application.
+This involves storing and updating data, as well as responding to the changes in it.
+
+With Solid, state management is handled through signals and subscribers.
+Signals are used to store and update data, while subscribers are used to respond to changes in the data.
+
+### Tracking changes
+
+Tracking changes involves monitoring any updates to the data and responding accordingly.
+This is done through the use of subscribers.
+
+When a signal is not accessed within a tracking scope, an update to the signal will not trigger an update.
+This happens because if a signal is not being tracked, it is not able to notify any subscribers of the change.
+
+```jsx
+const [count, setCount] = createSignal(0);
+
+console.log("Count:", count());
+
+setCount(1);
+
+// Output: Count: 0
+
+// `count` is not being tracked, so the console log will not update when `count` changes.
+```
+
+Since initialization is a **one-time event**, if a signal is accessed _outside of a tracking scope_, it will not be tracked.
+To track a signal, it must be accessed within the scope of a subscriber.
+Reactive primitives, such as [effects](/concepts/effects), can be used to create subscribers.
+
+```jsx
+const [count, setCount] = createSignal(0);
+
+createEffect(() => {
+ console.log("Count:", count());
+});
+
+setCount(1);
+
+// Output: Count: 0
+// Count: 1
+```
+
+### Updating the UI
+
+The UI of a Solid application is built using [JSX](/concepts/understanding-jsx).
+JSX creates a tracking scope behind the scenes, which allows signals to be tracked within the return statement of a component.
+
+```jsx
+function Counter() {
+ const [count, setCount] = createSignal(0);
+ const increment = () => setCount((prev) => prev + 1);
+
+ return (
+
+ Count: {count()}{" "}
+ {/* ✅ will update when `count()` changes. */}
+
+
+ );
+}
+```
+
+Components, much like other functions, will only run _once_.
+This means that if a signal is accessed outside of the return statement, it will run on initialization, but any updates to the signal will not trigger an update.
+
+```jsx
+function Counter() {
+ const [count, setCount] = createSignal(0);
+ const increment = () => setCount((prev) => prev + 1);
+
+ console.log("Count:", count()); // ❌ not tracked - only runs once during initialization.
+
+ createEffect(() => {
+ console.log(count()); // ✅ will update whenever `count()` changes.
+ });
+
+ return (
+
+ );
+}
+```
+
+To learn more about managing state in Solid, visit the [guide on state management](/guides/state-management).
+
+## Synchronous vs. asynchronous
+
+Reactive systems are designed to respond to changes in data.
+These responses can be immediate or delayed, depending on the nature of the system.
+Often, the choice between these two depends on the requirements of the application and the nature of the tasks involved.
+
+### Synchronous reactivity
+
+[Synchronous](https://developer.mozilla.org/en-US/docs/Glossary/Synchronous) reactivity is Solid's default reactivity mode, where a system responds to changes in a direct and linear fashion.
+When a signal changes, any corresponding subscribers are immediately updated in an ordered manner.
+
+With synchronous reactivity, the system is able to respond to changes in a predictable manner.
+This is useful in scenarios where the order of updates is important.
+For example, if a subscriber depends on another signal, it is important that the subscriber is updated after the signal it depends on.
+
+```jsx
+const [count, setCount] = createSignal(0);
+const [double, setDouble] = createSignal(0);
+
+createEffect(() => {
+ setDouble(count() * 2);
+});
+```
+
+In this example, the `double` signal will always be updated after `count` due to synchronous reactivity.
+This ensures that `double` is always up-to-date with the latest value of `count`.
+
+### Asynchronous reactivity
+
+[Asynchronous](https://developer.mozilla.org/en-US/docs/Glossary/Asynchronous) reactivity is when a system responds to changes in a delayed or non-linear fashion.
+When a signal changes, the corresponding subscribers are not immediately updated.
+Instead, the system waits for a specific event or task to complete before updating the subscribers.
+
+This is important in scenarios where subscribers depend on multiple signals.
+In these cases, updating one signal before another could result in data inconsistency.
+For example, if a subscriber depends on two signals, it is important that the subscriber is updated after both signals have been updated.
+Rather, the system waits for both signals to be updated before updating the subscriber.
+
+**Note:** When asynchronous reactivity is present, it is important to ensure that the system is able to handle the delay in updates.
+[`batch`](/reference/reactive-utilities/batch) can be used to delay an update so the subscriber runs after each signal has been updated.
+
+## Key concepts
+
+- Signals are the core elements of a reactive system.
+ They are responsible for storing and managing data.
+- Signals are both readable and writeable because of getters and setters.
+- Subscribers are automated responders that track changes in signals and update the system accordingly.
+- Signals and subscribers work together to ensure that the system is kept up-to-date with the latest data changes.
+- A reactive system is built on the principles of data-driven reactivity.
+ This means that the system's reactivity is driven by the data it is built on.
+- Reactive systems can be synchronous or asynchronous.
+
+If you want to dive deeper, visit the [guide on fine-grained reactivity](/advanced-concepts/fine-grained-reactivity).
+
+
+---
+title: Refs
+---
+
+Refs, or references, are a special attribute that can be attached to any element, and are used to reference a DOM element or a component instance.
+They are particularly useful when you need to access the DOM nodes directly or invoke methods on a component.
+
+## Accessing DOM elements
+
+One way of accessing DOM elements is through [element selectors](https://developer.mozilla.org/en-US/docs/Web/API/Document_object_model/Locating_DOM_elements_using_selectors) such as [`document.querySelector`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) or [`document.getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById).
+Since elements in Solid can be added or removed from the DOM based on state, you need to wait until the element is attached to the DOM before accessing it.
+This can be done by using [`onMount`](/reference/lifecycle/on-mount) to wait until the element is attached to the DOM before accessing it:
+
+Accessing DOM elements through element selectors is not recommended for this reason.
+As elements with the same selectors are added and removed from the DOM, the first element that matches the selector will be returned, which may not be the element you want.
+
+## JSX as a value
+
+JSX can be used as a value and assigned to a variable when looking to directly access DOM elements.
+
+```tsx
+function Component() {
+ const myElement =
My Element
+
+ return
{myElement}
+}
+```
+
+This lets you create and access DOM elements similar to [`document.createElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) but without having to wait until it is attached to the DOM.
+It can be used multiple times without having to worry about duplicate selectors.
+
+The downside of this approach is that it separates the element and any child elements from the rest of the JSX structure.
+This makes the component's JSX structure more difficult to read and understand.
+
+## Refs in Solid
+
+Solid provides a ref system to access DOM elements directly inside the JSX template, which keeps the structure of the elements intact.
+
+To use [`ref`](/reference/jsx-attributes/ref), you declare a variable and use it as the `ref` attribute:
+
+```tsx {6}
+function Component() {
+ let myElement;
+
+ return (
+
+
My Element
+
+ )
+}
+```
+
+These assignments occur at _creation time_ prior to the element being added to the DOM.
+If access to an element is needed before it is added to the DOM, you can use the callback form of `ref`:
+
+```jsx
+
{
+ myElement = el // el is created but not yet added to the DOM
+ }}>
+ My Element
+
+```
+
+
+In TypeScript, you must use a definitive assignment assertion.
+Since Solid takes care of assigning the variable when the component is rendered, this signals to TypeScript that the variable will be assigned, even if it can't
+confirm it.
+
+```tsx
+let myElement!: HTMLDivElement;
+```
+
+
+### Signals as refs
+
+[Signals](/concepts/signals) can also be used as refs.
+This is useful when you want to access the element directly, but the element may not exist when the component is first rendered, or may be removed from the DOM at some point.
+
+```jsx
+function App() {
+ const [show, setShow] = createSignal(false)
+ const [element, setElement] = createSignal()
+
+ return (
+
+
+
+
+
This is the ref element
+
+
+ )
+}
+```
+
+In this example, the paragraph element is only rendered when the `show` signal is `true`.
+When the component initializes, the paragraph element does not exist, so the `element` variable is not assigned.
+Once the `show` signal is set to `true`, the paragraph element is rendered, and the `element` variable is assigned to the paragraph element.
+
+You can see a detailed view of the ref update lifecycle in this [Solid playground example](https://playground.solidjs.com/anonymous/22a1abfa-a0f5-44a6-bbe6-40387cf63b95).
+
+## Forwarding refs
+
+Forwarding refs is a technique that allows you to pass a ref from a parent component to a child component.
+This is useful when you want to access the DOM element of a child component from the parent component.
+
+To forward a ref, you need to pass the ref to the child component, and then assign the ref to the child component's element.
+
+When a child component receives a `ref` attribute from its parent, the `ref` is passed as a callback function.
+This is regardless of whether the parent passed it as a simple assignment or a callback.
+
+Once the child component receives the `ref`, it can be assigned to the element that the child component wants to expose through the `ref` attribute.
+To access the `ref` in the child component, it is passed as a prop:
+
+```tsx
+// Parent component
+import { Canvas } from "./Canvas.jsx"
+
+function ParentComponent() {
+ let canvasRef
+
+ const animateCanvas = () => {
+ // Manipulate the canvas using canvasRef...
+ }
+
+ return (
+
+ )
+}
+```
+
+In this example, the `canvas` element is directly assigned the `ref` attribute through the `props.ref` variable.
+This forwards the reference to the parent component, giving it direct access to the `canvas` element.
+
+## Directives
+
+Directives allow the attachment of reusable behaviours to DOM elements.
+The [`use:`](/reference/jsx-attributes/use) prefix is used to denote these custom directives.
+Unlike props or attributes, directives operate at a lower level through providing fine-grained control over the elements they are attached to.
+
+Directives are like callback refs but they enable two extra features:
+
+- Having multiple directives on an element.
+- Passing in reactive data to the callback.
+
+A directive is essentially a function with a specific signature:
+
+```typescript
+function directive(element: Element, accessor: () => any): void
+
+```
+
+- `element`: The DOM element that the directive is applied to.
+- `accessor`: A function that gives access to the value(s) passed to the directive.
+
+The directive functions are called at render time, but are called before the element is added to the DOM.
+Due to this order, elements are fully primed with their attributes, properties, or event listeners, therefore minimizing unexpected behaviors or premature interactions.
+
+Within directives, you're able to perform a variety of tasks, including:
+
+- creating [signals](/concepts/signals)
+- initiating [effects](/guides/state-management#reacting-to-changes)
+- adding [event listeners](/concepts/components/event-handlers)
+- and more.
+
+To learn more about directives and how they work with TypeScript, refer to our [TypeScript for Solid guide](/configuration/typescript).
+
+
+---
+title: Signals
+order: 2
+---
+
+Signals are the primary means of [managing state](/concepts/intro-to-reactivity#state-management) in your Solid application.
+They provide a way to store and update values, and are the foundation of [reactivity](/concepts/intro-to-reactivity) in Solid.
+
+Signals can be used to represent any kind of state in your application, such as the current user, the current page, or the current theme.
+This can be any value, including primitive values such as strings and numbers, or complex values such as objects and arrays.
+
+## Creating a signal
+
+You can create a signal by calling the [`createSignal`](/reference/basic-reactivity/create-signal) function, which is imported from `solid-js`.
+This function takes an initial value as an argument, and returns a pair of functions: a **getter** function, and a **setter** function.
+
+```jsx
+import { createSignal } from "solid-js";
+
+const [count, setCount] = createSignal(0);
+// ^ getter ^ setter
+```
+
+
+ The syntax using `[` and `]` is called [array destructuring](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment).
+
+This lets you extract values from the array.
+In the context of `createSignal`, the first value is the getter function, and the second value is the setter function.
+
+
+
+## Accessing values
+
+The getter function returned by `createSignal` is used to access the value of the signal.
+You call this function with no arguments to get the current value of the signal:
+
+```jsx
+console.log(count()); // output: 0
+```
+
+## Updating values
+
+The setter function returned by `createSignal` is used to update the value of the signal.
+This function takes an argument that represents the new value of the signal:
+
+```jsx
+setCount(count() + 1);
+
+console.log(count()); // output: 1
+```
+
+The setter function can also take a function that passes the previous value.
+
+```jsx
+setCount((prevCount) => prevCount + 1);
+
+console.log(count()); // output: 1
+```
+
+## Reactivity
+
+Signals are reactive, which means that they automatically update when their value changes.
+When a signal is called within a [tracking scope](/concepts/intro-to-reactivity#tracking-changes), the signal adds the dependency to a list of subscribers.
+Once a signal's value changes, it notifies all of its dependencies of the change so they can re-evaluate their values and update accordingly.
+
+```jsx
+function Counter() {
+ const [count, setCount] = createSignal(0);
+ const increment = () => setCount((prev) => prev + 1);
+
+ return (
+
+ );
+}
+```
+
+
+A tracking scope can be created by [`createEffect`](/reference/basic-reactivity/create-effect) or [`createMemo`](/reference/basic-reactivity/create-memo), which are other Solid primitives.
+
+Both functions subscribe to the signals accessed within them, establishing a dependency relationship.
+Once this relationship is established, the function is notified whenever the signal changes.
+
+
+
+To learn more about how to use Signals in your application, visit our [state management guide](/guides/state-management).
+
+
+---
+title: Stores
+order: 6
+---
+
+Similar to [signals](/concepts/signals), stores are a state management primitive.
+However, while signals manage a single piece of state, stores create a centralized location to reduce code redundancy.
+Within Solid, these stores can spawn a collection of reactive signals, each corresponding to a particular property which can be useful when working with complex state.
+
+## Creating a store
+
+Stores can manage many data types, including: objects, arrays, strings, and numbers.
+
+Using JavaScript's [proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) mechanism, reactivity extends beyond just the top-level objects or arrays.
+With stores, you can now target nested properties and elements within these structures to create a dynamic tree of reactive data.
+
+```jsx
+import { createStore } from "solid-js/store"
+
+// Initialize store
+const [store, setStore] = createStore({
+ userCount: 3,
+ users: [
+ {
+ id: 0,
+ username: "felix909",
+ location: "England",
+ loggedIn: false,
+ },
+ {
+ id: 1,
+ username: "tracy634",
+ location: "Canada",
+ loggedIn: true,
+ },
+ {
+ id: 2,
+ username: "johny123",
+ location: "India",
+ loggedIn: true,
+ },
+ ],
+})
+```
+
+## Accessing store values
+
+Store properties can be accessed directly from the state proxy through directly referencing the targeted property:
+
+```jsx
+console.log(store.userCount) // Outputs: 3
+```
+
+Accessing stores within a tracking scope follows a similar pattern to signals.
+While signals are created using the [`createSignal`](/reference/basic-reactivity/create-signal) function and require calling the signal function to access their values, store values can be directly accessed without a function call.
+This provides access to the store's value directly within a tracking scope:
+
+```jsx
+const App = () => {
+ const [mySignal, setMySignal] = createSignal("This is a signal.")
+ const [store, setStore] = createStore({
+ userCount: 3,
+ users: [
+ {
+ id: 0,
+ username: "felix909",
+ location: "England",
+ loggedIn: false,
+ },
+ {
+ id: 1,
+ username: "tracy634",
+ location: "Canada",
+ loggedIn: true,
+ },
+ {
+ id: 2,
+ username: "johny123",
+ location: "India",
+ loggedIn: true,
+ },
+ ],
+ })
+ return (
+
+
Hello, {store.users[0].username}
{/* Accessing a store value */}
+ {mySignal()} {/* Accessing a signal */}
+
+ )
+}
+```
+
+When a store is created, it starts with the initial state but does _not_ immediately set up signals to track changes.
+These signals are created **lazily**, meaning they are only formed when accessed within a reactive context.
+
+Once data is used within a reactive context, such as within the return statement of a component function, computed property, or an effect, a signal is created and dependencies are established.
+
+For example, if you wanted to print out every new user, adding the console log below will not work because it is not within a tracked scope.
+
+
+```tsx ins={9}
+const App = () => {
+ const [store, setStore] = createStore({
+ userCount: 3,
+ users: [ ... ],
+ })
+
+ const addUser = () => { ... }
+
+ console.log(store.users.at(-1)) // This won't work
+
+ return (
+
+
Hello, {store.users[0].username}
+
User count: {store.userCount}
+
+
+ )
+}
+```
+
+Rather, this would need to be in a tracking scope, like inside a [`createEffect`](/reference/basic-reactivity/create-effect), so that a dependency is established.
+
+```tsx del={9} ins={10-12}
+const App = () => {
+ const [store, setStore] = createStore({
+ userCount: 3,
+ users: [ ... ],
+ })
+
+ const addUser = () => { ... }
+
+ console.log(store.users.at(-1))
+ createEffect(() => {
+ console.log(store.users.at(-1))
+ })
+
+ return (
+
+
Hello, {store.users[0].username}
+
User count: {store.userCount}
+
+
+ )
+}
+```
+
+## Modifying store values
+
+Updating values within a store is best accomplished using a setter provided by the `createStore` initialization.
+This setter allows for the modification of a specific key and its associated value, following the format `setStore(key, newValue)`:
+
+```jsx "setStore"
+const [store, setStore] = createStore({
+ userCount: 3,
+ users: [ ... ],
+})
+
+setStore("users", (currentUsers) => [
+ ...currentUsers,
+ {
+ id: 3,
+ username: "michael584",
+ location: "Nigeria",
+ loggedIn: false,
+ },
+])
+```
+
+The value of `userCount` could also be automatically updated whenever a new user is added to keep it synced with the users array:
+
+```tsx ins={11}
+const App = () => {
+ const [store, setStore] = createStore({
+ userCount: 3,
+ users: [ ... ],
+ })
+
+ const addUser = () => { ... }
+
+ createEffect(() => {
+ console.log(store.users.at(-1))
+ setStore("userCount", store.users.length)
+ })
+
+ return (
+
+
Hello, {store.users[0].username}
+
User count: {store.userCount}
+
+
+ )
+}
+```
+
+
+Separating the read and write capabilities of a store provides a valuable debugging advantage.
+
+This separation facilitates the tracking and control of the components that are accessing or changing the values.
+
+
+ A little hidden feature of stores is that you can also create nested stores to help with setting nested properties.
+
+```jsx
+ const [store, setStore] = createStore({
+ userCount: 3,
+ users: [ ... ],
+ })
+
+ const [users, setUsers] = createStore(store.users)
+
+ setUsers((currentUsers) => [
+ ...currentUsers,
+ {
+ id: 3,
+ username: "michael584",
+ location: "Nigeria",
+ loggedIn: false,
+ },
+ ])
+
+```
+ Changes made through `setUsers` will update the `store.users` property and reading `users` from this derived store will also be in sync with the values from `store.users`.
+
+ Note that the above relies on `store.users` to be set already in the existing store.
+
+
+
+## Path syntax flexibility
+
+Modifying a store using this method is referred to as "path syntax."
+In this approach, the initial arguments are used to specify the keys that lead to the target value you want to modify, while the last argument provides the new value.
+
+String keys are used to precisely target particular values with path syntax.
+By specifying these exact key names, you can directly retrieve the targeted information.
+However, path syntax goes beyond string keys and offers more versatility when accessing targeted values.
+
+Instead of employing the use of just string keys, there is the option of using an array of keys.
+This method grants you the ability to select multiple properties within the store, facilitating access to nested structures.
+Alternatively, you can use filtering functions to access keys based on dynamic conditions or specific rules.
+
+
+
+The flexibility in path syntax makes for efficient navigation, retrieval, and modification of data in your store, regardless of the store's complexity or the requirement for dynamic access scenarios within your application.
+
+## Modifying values in arrays
+
+Path syntax provides a convenient way to modify arrays, making it easier to access and update their elements.
+Instead of relying on discovering individual indices, path syntax introduces several powerful techniques for array manipulation.
+
+### Appending new values
+
+To append a new element to an array within a store, you specify the target array and set the index to the desired position.
+For example, if you wanted to append the new element to the end of the array, you would set the index to `array.length`:
+
+```jsx
+setStore("users", (otherUsers) => [
+ ...otherUsers,
+ {
+ id: 3,
+ username: "michael584",
+ location: "Nigeria",
+ loggedIn: false,
+ },
+])
+
+// can become
+
+setStore("users", store.users.length, {
+ id: 3,
+ username: "michael584",
+ location: "Nigeria",
+ loggedIn: false,
+})
+```
+
+### Range specification
+
+With path syntax, you can target a subset of elements to update or modify by specifying a range of indices.
+You can do this using an array of values:
+
+```jsx
+setStore("users", [1, 3], "loggedIn", false)
+```
+
+
+ If your *store* is an array, you can specify a range of indices using an object with `from` and `to` keys.
+
+```jsx
+const [store, setStore] = createStore([]) // A store that is an array
+...
+setStore({ from: 1, to: store.length - 1 }, "loggedIn", false)
+```
+
+In addition to this, including the `by` key, can help you perform iterative updates within an array, which can be useful when you want to update elements at regular intervals.
+This key defines the step size for index increments, similar to a [`for` loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for):
+
+```jsx
+setStore({ from: 0, to: store.length, by: 2 }, "loggedIn", false)
+```
+
+
+
+### Dynamic value assignment
+
+Path syntax also provides a way to set values within an array using functions instead of static values.
+These functions receive the old value as an argument, allowing you to compute the new value based on the existing one.
+This dynamic approach is particularly useful for complex transformations.
+
+```jsx
+setStore("users", 3, "loggedIn" , (loggedIn) => !loggedIn)
+```
+
+### Filtering values
+
+In scenarios where you want to update elements in an array based on a specific condition, you can pass a function as an argument.
+This function will act as a filter, allowing you to select elements that satisfy the condition.
+It receives the old value and index as arguments, providing the flexibility to make conditional updates.
+
+```jsx
+setStore("users", (user) => user.username.startsWith("t"), "loggedIn", false)
+```
+
+In addition to [`.startsWith`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith), you can use other array methods like [`.find`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find) to filter for the values that you need.
+
+## Modifying objects
+
+When using store setters to modify objects, if a new value is an object, it will be shallow merged with the existing value.
+What this refers to is that the properties of the existing object will be combined with the properties of the "new" object you are setting, updating any overlapping properties with the values from the new object.
+
+What this means, is that you can directly make the change to the store _without_ spreading out properties of the existing user object.
+
+```jsx
+setStore("users", 0, {
+ id: 109,
+})
+
+// is equivalent to
+
+setStore("users", 0, (user) => ({
+ ...user,
+ id: 109,
+}))
+```
+
+## Store utilities
+
+### Store updates with `produce`
+
+Rather than directly modifying a store with setters, Solid has the `produce` utility.
+This utility provides a way to work with data as if it were a [mutable](https://developer.mozilla.org/en-US/docs/Glossary/Mutable) JavaScript object.
+`produce` also provides a way to make changes to multiple properties at the same time which eliminates the need for multiple setter calls.
+
+```jsx
+import { produce } from "solid-js/store"
+
+// without produce
+setStore("users", 0, "username", "newUsername")
+setStore("users", 0, "location", "newLocation")
+
+// with produce
+setStore(
+ "users",
+ 0,
+ produce((user) => {
+ user.username = "newUsername"
+ user.location = "newLocation"
+ })
+)
+```
+
+`produce` and `setStore` do have distinct functionalities.
+While both can be used to modify the state, the key distinction lies in how they handle data.
+`produce` allows you to work with a temporary draft of the state, apply the changes, then produce a new [immutable](https://developer.mozilla.org/en-US/docs/Glossary/Immutable) version of the store.
+Comparatively, `setStore` provides a more straightforward way to update the store directly, without creating a new version.
+
+It's important to note, however, `produce` is specifically designed to work with **arrays** and **objects**.
+Other collection types, such as JavaScript [Sets](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) and [Maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map), are not compatible with this utility.
+
+### Data integration with `reconcile`
+
+When new information needs to be merged into an existing store `reconcile` can be useful.
+`reconcile` will determine the differences between new and existing data and initiate updates only when there are _changed_ values, thereby avoiding unnecessary updates.
+
+```jsx
+const { createStore, reconcile } from "solid-js/stores"
+
+const [data, setData] = createStore({
+ animals: ['cat', 'dog', 'bird', 'gorilla']
+})
+
+const newData = getNewData() // eg. contains ['cat', 'dog', 'bird', 'gorilla', 'koala']
+setData('animals', reconcile(newData))
+
+```
+
+In this example, the store will look for the differences between the existing and incoming data sets.
+Consequently, only `'koala'` - the new edition - will cause an update.
+
+### Extracting raw data with `unwrap`
+
+When there is a need for dealing with data outside of a reactive context, the `unwrap` utility offers a way to transform a store to a standard [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object).
+This conversion serves several important purposes.
+
+Firstly, it provides a snapshot of the current state without the processing overhead associated with reactivity.
+This can be useful in situations where an unaltered, non-reactive view of the data is needed.
+Additionally, `unwrap` provides a means to interface with third-party libraries or tools that anticipate regular JavaScript objects.
+This utility acts as a bridge to facilitate smooth integrations with external components and simplifies the incorporation of stores into various applications and workflows.
+
+```jsx
+import { createStore, unwrap } from "solid-js/store"
+
+const [data, setData] = createStore({
+ animals: ["cat", "dog", "bird", "gorilla"],
+})
+
+const rawData = unwrap(data)
+```
+
+To learn more about how to use Stores in practice, visit the [guide on complex state management](/guides/complex-state-management).
+
+
+---
+title: Understanding JSX
+order: 2
+---
+
+JSX is an extension for JavaScript.
+It allows you to write HTML-like code inside your JavaScript file which keeps your rendering logic and content in the same place.
+This provides a concise and readable way to create and represent components.
+
+## How Solid uses JSX
+
+Solid was designed to align closely with HTML standards.
+
+```jsx
+const element =
I'm JSX!!
+```
+
+It offers a distinct advantage, however: to copy/paste solutions from resources like Stack Overflow; and to allow direct usage of templates from design tools.
+Solid sets itself apart by using JSX immediately as it returns [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) elements.
+This lets you use dynamic expressions within your HTML by allowing variables and functions to be references with the use of curly braces (`{ }`):
+
+```jsx
+const Component = () => {
+ const animal = { breed: "cat", name: "Midnight" }
+
+ return (
+
+ I have a {animal.breed} named {animal.name}!
+
+ )
+}
+```
+
+This means JavaScript content can be rendered on web pages based on an application's state or logic.
+
+Additionally, Solid's [reactive](/concepts/intro-to-reactivity) system introduces [fine-grained reactivity](/advanced-concepts/fine-grained-reactivity) with JSX.
+This updates only the necessary parts of the DOM when changes occur in the underlying state.
+
+## Using JSX in Solid
+
+### Return a single root element
+
+Where HTML lets you have disconnected tags at the top level, JSX requires that a component to return a single root element.
+
+
+When working with JSX, parts of your code are translated into structured HTML that is placed at the start of the file.
+Static elements are processed differently from dynamic ones, which might change based on data or user actions.
+For dynamic elements, special markers are added for better handling during rendering.
+
+Having a single root creates a consistent and manageable hierarchy to optimize rendering and updates.
+
+
+JSX maintains the familiar nested, tree-like structure found in HTML.
+As a result, parent-child relationships between elements become easier to follow.
+
+### Close all tags
+
+Self-closing tags are a must in JSX.
+Unlike in HTML, where elements like ``, ``, or ` ` don't require explicit closure, JSX requires consistent self-closing tags.
+This helps to avoid potential rendering issues.
+
+```jsx
+
+```
+
+### Properties vs. attributes
+
+HTML attributes and JSX properties may seem similar, but they serve different purposes and behave differently.
+Both offer ways to specify configurations or pass information.
+However, HTML is used for standard web content and JSX creates Solid's component logic.
+
+#### HTML attributes
+
+[HTML attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes) are values set directly on HTML elements.
+They provide additional information about an element to guide its initial behavior and state.
+These attributes are often translated into properties on DOM objects once the browser parses the HTML.
+
+In JSX files, HTML attributes are used much like regular HTML, with a few key differences due to the blend of HTML and JavaScript:
+
+- Event listeners such as `onClick` can be in camelCase or lowercase.
+ (**Note:** When using ESLint, you will get a warning if you use lowercase.)
+- In cases where you can dynamically specify a value, you can replace the `"` and `"` with curly braces (`{ }`):
+
+```jsx
+
+```
+
+
+ If you wish to pass objects in JSX, such as with inline styling, you will have to use double curly braces (`{{ }}`).
+
+```jsx
+
+```
+
+
+### JSX properties (props)
+
+JSX properties, commonly known as "props," help with the passing of data and configurations to components within an application.
+They connect the component with the data it requires, for seamless data flows and dynamic interactions.
+
+#### Core concepts
+
+- **Static props**:
+ In Solid's JSX, static props are integrated directly into the HTML by cloning the template and using them as attributes.
+
+ - **Dynamic props**:
+ Dynamic props rely on state, allowing the content or properties to be dynamic.
+ An example is changing the style of an element in response to interactions within an application.
+ This can be expressed in the form of signals (`value={value()}`).
+
+- **Data transfer**:
+ Props are also used to fill components with data that comes from resources, like [`createResource`](/reference/basic-reactivity/create-resource) calls.
+ This results in components that react in real-time to data changes.
+
+
+Expressions, whether fixed or dynamic, get applied *in the order defined within the JSX*.
+This works for a wide range of DOM elements, but will not work with elements that require attributes to be defined in a special order, such as input types with `type='range'`.
+
+When order influences an element's behavior, users must define the expressions in the order that the element is expected.
+
+
+For how to use props effectively in Solid, explore the [props page](/concepts/components/props).
+
+
+---
+title: Overview
+mainNavExclude: true
+---
+
+# Overview
+
+Solid is a modern JavaScript framework designed to build responsive and high-performing user interfaces (UI).
+It prioritizes a simple and predictable development experience, making it a great choice for developers of all skill levels.
+
+## What is Solid?
+
+As a JavaScript framework, Solid embraces reactivity and fine-grained updates.
+
+Reactivity, in programming, refers to an applications' ability to respond to changes in data or user interactions.
+
+Traditionally, when a change occurs, the entire web page would need to reload to display the updated information.
+In contrast, when using a fine-grained reactive system, updates are only applied to the parts of the page that need to be updated.
+
+Solid adopts the concept of fine-grained reactivity, updating only when the data the application depends on changes.
+This decreases work and can result in faster load times and a smoother user experience overall.
+
+## Advantages of using Solid
+
+- **Performant**: Fine-grained reactivity allows Solid to update only what has changed, resulting in faster load times and smoother performance overall.
+
+- **Powerful**: Using less memory and processing power, Solid is capable of creating complex applications without compromising on functionality.
+ This also gives developers the flexibility over how and when updates happen.
+
+- **Pragmatic**: Rather than sticking to rigid structures or methods, Solid provides the freedom to choose the strategies and practices that work best for you.
+
+- **Productive**: Regardless of experience level, Solid's clear and predictable API makes developers' work simpler and more efficient.
+
+Solid aims to strike a balance between speed, efficiency, power, and flexibility, all while providing a developer-friendly environment.
+This combination of features makes it a great choice to build responsive and high-performing UIs.
+
+## Quick links
+
+
+
+ Learn the basics of Solid through this interactive tutorial.
+
+
+ Start your first project with a template that fits your needs.
+
+
+ Explore the Solid ecosystem and find useful tools and libraries.
+
+
+ Help improve Solid by contributing to the documentation.
+
+
+
+_Find our API documentation under the **Reference** tab_
+
+Join the [Solid community on Discord](https://discord.com/invite/solidjs) to share your projects or get help from our community!
+
+
+
+
+
+---
+title: Quick start
+---
+
+## Solid playgrounds
+
+Experience Solid in your browser by visiting our [interactive playground](https://playground.solidjs.com/).
+
+Additionally, we offer a [JavaScript](https://stackblitz.com/github/solidjs/templates/tree/master/js) and [Typescript](https://stackblitz.com/github/solidjs/templates/tree/master/ts) Stackblitz starters, which provide a web-based development environment to get you started.
+
+## Creating a Solid application
+
+
+
+ - Familiarity with the command line
+ - Install [Node.js](https://nodejs.org/en) or [Deno](https://deno.com)
+
+
+
+Solid offers convenient project templates that can help kickstart your development.
+To get an application running, follow the steps below based on the language you prefer to use.
+
+### For JavaScript projects
+
+1. Run the following command in your terminal to get the JavaScript starter template:
+
+
+
+```bash frame="none"
+deno -A npm:degit solidjs/templates/js my-app
+```
+
+
+
+
+2. Navigate to your application's directory:
+
+```bash frame="none"
+cd my-app
+```
+
+3. Install the necessary dependencies:
+
+
+
+```bash frame="none"
+npm install
+```
+
+
+
+```bash frame="none"
+yarn install
+```
+
+
+
+```bash frame="none"
+pnpm install
+```
+
+
+
+```bash frame="none"
+bun install
+```
+
+
+
+```bash frame="none"
+deno install
+```
+
+
+
+4. Run the application:
+
+
+
+```bash frame="none"
+npm run dev
+```
+
+
+
+```bash frame="none"
+yarn dev
+```
+
+
+
+```bash frame="none"
+pnpm dev
+```
+
+
+
+```bash frame="none"
+bun dev
+```
+
+
+```bash frame="none"
+deno task dev
+```
+
+
+
+This will start the development server.
+Now, you can open your browser and navigate to `localhost:3000` to see your application running.
+
+### For TypeScript projects
+
+1. To use a TypeScript template, run the following command in your terminal:
+
+
+
+```bash frame="none"
+deno -A npm:degit solidjs/templates/ts my-app
+```
+
+
+
+2. Navigate to your application's directory:
+
+```bash frame="none"
+cd my-app
+```
+
+3. Install the necessary dependencies:
+
+
+
+```bash frame="none"
+npm install
+```
+
+
+
+```bash frame="none"
+yarn install
+```
+
+
+
+```bash frame="none"
+pnpm install
+```
+
+
+
+```bash frame="none"
+bun install
+```
+
+
+```bash frame="none"
+deno install
+```
+
+
+
+4. Run the application:
+
+
+
+```bash frame="none"
+npm run dev
+```
+
+
+
+```bash frame="none"
+yarn dev
+```
+
+
+
+```bash frame="none"
+pnpm dev
+```
+
+
+
+```bash frame="none"
+bun dev
+```
+
+
+```bash frame="none"
+deno task dev
+```
+
+
+
+
+This will start the development server.
+Now, you can open your browser and navigate to `localhost:3000` to see your application running.
+
+### Explore more templates
+
+Solid offers a variety of Vite templates to streamline your development process.
+These resources are available on [GitHub](https://github.com/solidjs/templates).
+
+
+---
+title: createEffect
+---
+
+```tsx
+import { createEffect } from "solid-js"
+
+function createEffect(fn: (v: T) => T, value?: T): void
+
+```
+
+Effects are a general way to make arbitrary code ("side effects") run whenever dependencies change, e.g., to modify the DOM manually.
+`createEffect` creates a new computation that runs the given function in a tracking scope, thus automatically tracking its dependencies, and automatically reruns the function whenever the dependencies update.
+
+For example:
+
+```tsx
+const [a, setA] = createSignal(initialValue)
+
+// effect that depends on signal `a`
+createEffect(() => doSideEffect(a()))
+```
+
+The effect will run whenever `a` changes value.
+
+The effect will also run once, immediately after it is created, to initialize the DOM to the correct state. This is called the "mounting" phase.
+However, we recommend using `onMount` instead, which is a more explicit way to express this.
+
+The effect callback can return a value, which will be passed as the `prev` argument to the next invocation of the effect.
+This is useful for memoizing values that are expensive to compute. For example:
+
+```tsx
+const [a, setA] = createSignal(initialValue)
+
+// effect that depends on signal `a`
+createEffect((prevSum) => {
+ // do something with `a` and `prevSum`
+ const sum = a() + b()
+ if (sum !== prevSum) console.log("sum changed to", sum)
+ return sum
+}, 0)
+// ^ the initial value of the effect is 0
+```
+
+Effects are meant primarily for side effects that read but don't write to the reactive system: it's best to avoid setting signals in effects, which without care can cause additional rendering or even infinite effect loops. Instead, prefer using [createMemo](/reference/basic-reactivity/create-memo) to compute new values that depend on other reactive values, so the reactive system knows what depends on what, and can optimize accordingly.
+If you do end up setting a signal within an effect, computations subscribed to that signal will be executed only once the effect completes; see [`batch`](/reference/reactive-utilities/batch) for more detail.
+
+The first execution of the effect function is not immediate; it's scheduled to run after the current rendering phase (e.g., after calling the function passed to [render](/reference/rendering/render), [createRoot](/reference/reactive-utilities/create-root), or [runWithOwner](/reference/reactive-utilities/run-with-owner)).
+If you want to wait for the first execution to occur, use [queueMicrotask](https://developer.mozilla.org/en-US/docs/Web/API/queueMicrotask) (which runs before the browser renders the DOM) or `await Promise.resolve()` or `setTimeout(..., 0)` (which runs after browser rendering).
+
+```tsx
+// assume this code is in a component function, so is part of a rendering phase
+const [count, setCount] = createSignal(0)
+
+// this effect prints count at the beginning and when it changes
+createEffect(() => console.log("count =", count()))
+// effect won't run yet
+console.log("hello")
+setCount(1) // effect still won't run yet
+setCount(2) // effect still won't run yet
+
+queueMicrotask(() => {
+ // now `count = 2` will print
+ console.log("microtask")
+ setCount(3) // immediately prints `count = 3`
+ console.log("goodbye")
+})
+
+// --- overall output: ---
+// hello
+// count = 2
+// microtask
+// count = 3
+// goodbye
+```
+
+This delay in first execution is useful because it means an effect defined in a component scope runs after the JSX returned by the component gets added to the DOM.
+In particular, [refs](/reference/jsx-attributes/ref) will already be set.
+Thus you can use an effect to manipulate the DOM manually, call vanilla JS libraries, or other side effects.
+
+Note that the first run of the effect still runs before the browser renders the DOM to the screen (similar to React's `useLayoutEffect`).
+If you need to wait until after rendering (e.g., to measure the rendering), you can use `await Promise.resolve()` (or `Promise.resolve().then(...)`), but note that subsequent use of reactive state (such as signals) will not trigger the effect to rerun, as tracking is not possible after an async function uses `await`.
+Thus you should use all dependencies before the promise.
+
+If you'd rather an effect run immediately even for its first run, use [createRenderEffect](/reference/secondary-primitives/create-render-effect) or [createComputed](/reference/secondary-primitives/create-computed).
+
+You can clean up your side effects in between executions of the effect function by calling [onCleanup](/reference/lifecycle/on-cleanup) inside the effect function.
+Such a cleanup function gets called both in between effect executions and when the effect gets disposed (e.g., the containing component unmounts).
+For example:
+
+```tsx
+// listen to event dynamically given by eventName signal
+createEffect(() => {
+ const event = eventName()
+ const callback = (e) => console.log(e)
+ ref.addEventListener(event, callback)
+ onCleanup(() => ref.removeEventListener(event, callback))
+})
+```
+
+## Arguments
+
+- `fn` - The function to run in a tracking scope. It can return a value, which will be passed as the `prev` argument to the next invocation of the effect.
+- `value` - The initial value of the effect. This is useful for memoizing values that are expensive to compute.
+
+
+---
+title: createMemo
+---
+
+Memos let you efficiently use a derived value in many reactive computations.
+`createMemo` creates a readonly reactive value equal to the return value of the given function and makes sure that function only gets executed when its dependencies change.
+
+```tsx
+import { createMemo } from "solid-js"
+
+function createMemo(
+ fn: (v: T) => T,
+ value?: T,
+ options?: { equals?: false | ((prev: T, next: T) => boolean) }
+): () => T
+
+```
+
+Here's an example of how createMemo can be used:
+
+```ts
+const value = createMemo(() => computeExpensiveValue(a(), b()))
+
+//read the value
+value()
+```
+
+In Solid, you often don't need to wrap functions in memos; you can alternatively just define and call a regular function to get similar reactive behavior.
+The main difference is when you call the function in multiple reactive settings.
+In this case, when the function's dependencies update, the function will get called multiple times unless it is wrapped in createMemo.
+For example:
+
+```tsx
+const user = createMemo(() => searchForUser(username()))
+// compare with: const user = () => searchForUser(username());
+return (
+
+
Your name is {user()?.name}
+
+ Your email is {user()?.email}
+
+
+)
+```
+
+When the username signal updates, searchForUser will get called just once.
+If the returned user actually changed, the user memo updates, and then both list items will update automatically.
+
+If we had instead defined user as a plain function `() => searchForUser(username())`, then `searchForUser` would have been called twice, once when updating each list item.
+
+Another key difference is that a memo can shield dependents from updating when the memo's dependencies change but the resulting memo value doesn't.
+Like [createSignal](/reference/basic-reactivity/create-signal), the derived signal made by `createMemo` updates (and triggers dependents to rerun) only when the value returned by the memo function actually changes from the previous value, according to JavaScript's `===` operator.
+Alternatively, you can pass an options object with `equals` set to false to always update the memo when its dependencies change, or you can pass your own `equals` function for testing equality.
+
+The memo function is called with an argument equal to the value returned from the previous execution of the memo function, or, on the first call, equal to the optional second argument to `createMemo`.
+This is useful for reducing computations, such as:
+
+```tsx
+// track the sum of all values taken on by input() as it updates
+const sum = createMemo((prev) => input() + prev, 0)
+```
+
+The memo function should not change other signals by calling setters (it should be "pure").
+This enables Solid to optimize the execution order of memo updates according to their dependency graph, so that all memos can update at most once in response to a dependency change.
+
+## Options and arguments
+
+| Name | Type | Description |
+| :------ | :------------------------------------------------------ | :------------------------------------------------------------- |
+| fn | `(v: T) => T` | The function to memoize. |
+| value | `T` | The initial value of the memo. |
+| options | `{ equals?: false \| ((prev: T, next: T) => boolean) }` | An optional object with an `equals` function to test equality. |
+
+
+---
+title: createResource
+---
+
+`createResource` takes an asynchronous fetcher function and returns a signal that is updated with the resulting data when the fetcher completes.
+
+There are two ways to use `createResource`: you can pass the fetcher function as the sole argument, or you can additionally pass a source signal as the first argument.
+The source signal will retrigger the fetcher whenever it changes, and its value will be passed to the fetcher.
+
+```tsx
+const [data, { mutate, refetch }] = createResource(fetchData)
+```
+
+```tsx
+const [data, { mutate, refetch }] = createResource(source, fetchData)
+```
+
+In these snippets, the fetcher is the function `fetchData`, and `data()` is undefined until `fetchData` finishes resolving.
+In the first case, `fetchData` will be called immediately.
+In the second, `fetchData` will be called as soon as `source` has any value other than false, null, or undefined.
+It will be called again whenever the value of `source` changes, and that value will always be passed to `fetchData` as its first argument.
+
+You can call `mutate` to directly update the `data` signal (it works like any other signal setter).
+You can also call refetch to rerun the fetcher directly, and pass an optional argument to provide additional info to the fetcher e.g `refetch(info)`.
+
+`data` works like a normal signal getter: use `data()` to read the last returned value of `fetchData`.
+But it also has extra reactive properties: `data.loading` tells you if the fetcher has been called but not returned, and `data.error` tells you if the request has errored out; if so, it contains the error thrown by the fetcher.
+(Note: if you anticipate errors, you may want to wrap `createResource` in an [ErrorBoundary](/reference/components/error-boundary).)
+
+As of **v1.4.0**, `data.latest` will return the last returned value and won't trigger [Suspense](/reference/components/suspense) and [transitions](#TODO); if no value has been returned yet, `data.latest` acts the same as `data()`.
+This can be useful if you want to show the out-of-date data while the new data is loading.
+
+`loading`, `error`, and `latest` are reactive getters and can be tracked.
+
+## The fetcher
+
+The `fetcher` is the async function that you provide to `createResource` to actually fetch the data.
+It is passed two arguments: the value of the source signal (if provided), and an info object with two properties: `value` and `refetching`.
+The `value` property tells you the previously fetched value.
+The `refetching` property is true if the `fetcher` was triggered using the refetch function and false otherwise.
+If the `refetch` function was called with an argument (`refetch(info)`), refetching is set to that argument.
+
+```tsx
+async function fetchData(source, { value, refetching }) {
+ // Fetch the data and return a value.
+ //`source` tells you the current value of the source signal;
+ //`value` tells you the last returned value of the fetcher;
+ //`refetching` is true when the fetcher is triggered by calling `refetch()`,
+ // or equal to the optional data passed: `refetch(info)`
+}
+
+const [data, { mutate, refetch }] = createResource(getQuery, fetchData)
+
+// read value
+data()
+
+// check if loading
+data.loading
+
+// check if errored
+data.error
+
+// directly set value without creating promise
+mutate(optimisticValue)
+
+// refetch the last request explicitly
+refetch()
+
+```
+
+## Version 1.4.0 and Later
+
+#### v1.4.0
+
+If you're using `renderToStream`, you can tell Solid to wait for a resource before flushing the stream using the `deferStream` option:
+
+```tsx
+// fetches a user and streams content as soon as possible
+const [user] = createResource(() => params.id, fetchUser)
+
+// fetches a user but only streams content after this resource has loaded
+const [user] = createResource(() => params.id, fetchUser, {
+ deferStream: true,
+})
+```
+
+#### v1.5.0
+
+1. We've added a new state field which covers a more detailed view of the Resource state beyond `loading` and `error`.
+You can now check whether a Resource is `unresolved`, `pending`, `ready`, `refreshing`, or `error`.
+
+| State | Value resolved | Loading | Has error |
+| ------------ | -------------- | ------- | --------- |
+| `unresolved` | No | No | No |
+| `pending` | No | Yes | No |
+| `ready` | Yes | No | No |
+| `refreshing` | Yes | Yes | No |
+| `error` | No | No | Yes |
+
+2. When server-rendering resources, especially when embedding Solid in other systems that fetch data before rendering, you might want to initialize the resource with this prefetched value instead of fetching again and having the resource serialize it in its own state.
+You can use the new `ssrLoadFrom` option for this.
+Instead of using the default `server` value, you can pass `initial` and the resource will use `initialValue` as if it were the result of the first fetch for both SSR and hydration.
+
+```tsx
+const [data, { mutate, refetch }] = createResource(() => params.id, fetchUser, {
+ initialValue: preloadedData,
+ ssrLoadFrom: "initial",
+})
+```
+
+3. Resources can be set with custom defined storage with the same signature as a Signal by using the storage option.
+For example using a custom reconciling store could be done this way:
+
+```tsx
+function createDeepSignal(value: T): Signal {
+ const [store, setStore] = createStore({
+ value,
+ })
+ return [
+ () => store.value,
+ (v: T) => {
+ const unwrapped = unwrap(store.value)
+ typeof v === "function" && (v = v(unwrapped))
+ setStore("value", reconcile(v))
+ return store.value
+ },
+ ] as Signal
+}
+
+const [resource] = createResource(fetcher, {
+ storage: createDeepSignal,
+})
+```
+
+This option is still experimental and may change in the future.
+
+## Options
+
+The `createResource` function takes an optional third argument, an options object. The options are:
+
+| Name | Type | Default | Description |
+| ------------ | ----------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| name | `string` | `undefined` | A name for the resource. This is used for debugging purposes. |
+| deferStream | `boolean` | `false` | If true, Solid will wait for the resource to resolve before flushing the stream. |
+| initialValue | `any` | `undefined` | The initial value of the resource. |
+| onHydrated | `function` | `undefined` | A callback that is called when the resource is hydrated. |
+| ssrLoadFrom | `"server" \| "initial"` | `"server"` | The source of the initial value for SSR. If set to `"initial"`, the resource will use the `initialValue` option instead of the value returned by the fetcher. |
+| storage | `function` | `createSignal` | A function that returns a signal. This can be used to create a custom storage for the resource. This is still experimental |
+
+## Note for TypeScript users
+
+The function and type definitions for `createResource` are as follows:
+
+```tsx
+import { createResource } from "solid-js"
+import type { ResourceReturn, ResourceOptions } from "solid-js"
+
+type ResourceReturn = [
+ {
+ (): T | undefined
+ state: "unresolved" | "pending" | "ready" | "refreshing" | "errored"
+ loading: boolean
+ error: any
+ latest: T | undefined
+ },
+ {
+ mutate: (v: T | undefined) => T | undefined
+ refetch: (info: unknown) => Promise | T
+ }
+]
+
+type ResourceOptions = {
+ initialValue?: T
+ name?: string
+ deferStream?: boolean
+ ssrLoadFrom?: "initial" | "server"
+ storage?: (
+ init: T | undefined
+ ) => [Accessor, Setter]
+ onHydrated?: (k: S | undefined, info: { value: T | undefined }) => void
+}
+
+function createResource(
+ fetcher: (
+ k: U,
+ info: { value: T | undefined; refetching: boolean | unknown }
+ ) => T | Promise,
+ options?: ResourceOptions
+): ResourceReturn
+
+function createResource(
+ source: U | false | null | (() => U | false | null),
+ fetcher: (
+ k: U,
+ info: { value: T | undefined; refetching: boolean | unknown }
+ ) => T | Promise,
+ options?: ResourceOptions
+): ResourceReturn
+
+```
+
+
+---
+title: createSignal
+---
+
+Signals are the most basic reactive primitive.
+They track a single value (which can be a value of any type) that changes over time.
+
+```tsx
+import { createSignal } from "solid-js"
+
+function createSignal(
+ initialValue: T,
+ options?: {
+ equals?: false | ((prev: T, next: T) => boolean)
+ name?: string
+ internal?: boolean
+ }
+): [get: () => T, set: (v: T) => T]
+
+// available types for return value of createSignal:
+import type { Signal, Accessor, Setter } from "solid-js"
+type Signal = [get: Accessor, set: Setter]
+type Accessor = () => T
+type Setter = (v: T | ((prev?: T) => T)) => T
+
+```
+
+The Signal's value starts out equal to the passed first argument `initialValue` (or undefined if there are no arguments).
+The `createSignal` function returns a pair of functions as a two-element array: a getter (or accessor) and a setter.
+In typical use, you would destructure this array into a named Signal like so:
+
+```tsx
+const [count, setCount] = createSignal(0)
+const [ready, setReady] = createSignal(false)
+```
+
+Calling the getter (e.g., `count()` or `ready()`) returns the current value of the Signal.
+
+Crucial to automatic dependency tracking, calling the getter within a tracking scope causes the calling function to depend on this Signal, so that function will rerun if the Signal gets updated.
+
+Calling the setter (e.g., `setCount(nextCount)` or `setReady(nextReady)`) sets the Signal's value and updates the Signal (triggering dependents to rerun) if the value actually changed (see details below).
+The setter takes either the new value for the signal or a function that maps the previous value of the signal to a new value as its only argument.
+The updated value is also returned by the setter. As an example:
+
+```tsx
+// read signal's current value, and
+// depend on signal if in a tracking scope
+// (but nonreactive outside of a tracking scope):
+const currentCount = count()
+
+// or wrap any computation with a function,
+// and this function can be used in a tracking scope:
+const doubledCount = () => 2 * count()
+
+// or build a tracking scope and depend on signal:
+const countDisplay =
{count()}
+
+// write signal by providing a value:
+setReady(true)
+
+// write signal by providing a function setter:
+const newCount = setCount((prev) => prev + 1)
+
+```
+
+
+ If you want to store a function in a Signal you must use the function form:
+
+ ```tsx
+ setValue(() => myFunction);
+ ```
+
+ However, functions are not treated specially as the `initialValue` argument to `createSignal`, so you can pass a
+ function initial value as is:
+
+ ```tsx
+ const [func, setFunc] = createSignal(myFunction);
+ ```
+
+
+
+## Options
+
+| Name | Type | Default | Description |
+| ---------- | ------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `equals` | `false \| ((prev: T, next: T) => boolean)` | `===` | A function that determines whether the Signal's value has changed. If the function returns true, the Signal's value will not be updated and dependents will not rerun. If the function returns false, the Signal's value will be updated and dependents will rerun. |
+| `name` | `string` | | A name for the Signal. This is useful for debugging. |
+| `internal` | `boolean` | `false` | If true, the Signal will not be accessible in the devtools. |
+
+### `equals`
+
+The `equals` option can be used to customize the equality check used to determine whether the Signal's value has changed.
+By default, the equality check is a strict equality check (`===`).
+If you want to use a different equality check, you can pass a custom function as the `equals` option.
+The custom function will be called with the previous and next values of the Signal as arguments.
+If the function returns true, the Signal's value will not be updated and dependents will not rerun.
+If the function returns false, the Signal's value will be updated and dependents will rerun.
+
+```tsx
+const [count, setCount] = createSignal(0, {
+ equals: (prev, next) => prev === next,
+})
+```
+
+Here are some examples of this option in use:
+
+```tsx
+// use { equals: false } to allow modifying object in-place;
+// normally this wouldn't be seen as an update because the
+// object has the same identity before and after change
+const [object, setObject] = createSignal({ count: 0 }, { equals: false })
+setObject((current) => {
+ current.count += 1
+ current.updated = new Date()
+ return current
+})
+
+// use { equals: false } to create a signal that acts as a trigger without storing a value:
+const [depend, rerun] = createSignal(undefined, { equals: false })
+// now calling depend() in a tracking scope
+// makes that scope rerun whenever rerun() gets called
+
+// define equality based on string length:
+const [myString, setMyString] = createSignal("string", {
+ equals: (newVal, oldVal) => newVal.length === oldVal.length,
+})
+
+setMyString("string") // considered equal to the last value and won't cause updates
+setMyString("stranger") // considered different and will cause updates
+```
+
+### `name`
+
+The `name` option can be used to give the Signal a name.
+This is useful for debugging. The name will be displayed in the devtools.
+
+```tsx
+const [count, setCount] = createSignal(0, { name: "count" })
+```
+
+### `internal`
+
+The `internal` option can be used to hide the Signal from the devtools.
+This is useful for Signals that are used internally by a component and should not be exposed to the user.
+
+```tsx
+const [count, setCount] = createSignal(0, { internal: true })
+```
+
+
+---
+title: children
+---
+
+```tsx
+import { children } from "solid-js";
+import type { JSX, ResolvedChildren } from "solid-js";
+
+function children(fn: () => JSX.Element): () => ResolvedChildren
+
+```
+
+The `children` helper is used for more complex interactions with props.
+When you're not just passing children to another component using `props.children` once in JSX, you should use `children`.
+Props are normally passed in via a getter for `props.children` in this manner:
+
+```tsx
+const resolved = children(() => props.children)
+```
+
+The return value is a [memo](/reference/basic-reactivity/create-memo) evaluating to the resolved children, which updates whenever the children change.
+Using this memo instead of accessing `props.children` directly has some important advantages in some scenarios.
+The underlying issue is that, when you specify component children via JSX, Solid automatically defines `props.children` as a property getter, so that the children are created (in particular, DOM is created) whenever `props.children` gets accessed.
+
+Two particular consequences:
+
+1. If you access `props.children` multiple times, the children (and associated DOM) get created multiple times.
+This is useful if you want the DOM to be duplicated (as DOM nodes can appear in only one parent element), but in many cases it creates redundant DOM nodes.
+If you instead call `resolved()` multiple times, you re-use the same children.
+
+2. If you access `props.children` outside of a tracking scope (e.g., in an event handler), then you create children that will never be cleaned up.
+If you instead call `resolved()`, you re-use the already resolved children.
+You also guarantee that the children are tracked in the current component, as opposed to another tracking scope such as another component.
+
+In addition, the `children` helper "resolves" children by calling argumentless functions and flattening arrays of arrays into an array.
+For example, a child specified with JSX like `{signal() * 2}` gets wrapped into a getter function `() => count() * 2` in `props.children`, but gets evaluated to an actual number in resolved, properly depending on a count signal.
+
+If the given `props.children` is not an array (which occurs when the JSX tag has a single child), then the `children` helper will not normalize it into an array.
+This is useful behavior e.g. when the intention is to pass a single function as a child, which can be detected via `typeof resolved() === 'function'`.
+If you want to normalize to an array, the returned memo has a `toArray` method _(new in 1.5)_.
+
+In most cases, you don't need (and in some cases, don't want) to use the `children` helper if you're just passing `props.children` on to another component or element via JSX:
+
+```tsx
+const Wrapper = (props) => {
+ return
{props.children}
+}
+```
+
+An important aspect of the `children` helper is that it forces the children to be created and resolved, as it accesses `props.children` immediately.
+This can be undesirable for conditional rendering, e.g., when using the children within a [``](/reference/components/show) component.
+For example, the following code always evaluates the children:
+
+```tsx
+const resolved = children(() => props.children)
+
+return {resolved()}
+```
+
+To evaluate the children only when `` would render them, you can push the call to children inside a component or a function within ``, which only evaluates its children when `when` condition is true.
+Another nice workaround is to pass `props.children` to the children helper only when you actually want to evaluate the children:
+
+```tsx
+const resolved = children(() => visible() && props.children)
+```
+
+
+---
+title: createContext
+order: 5
+---
+
+
+Context provides a form of dependency injection in Solid.
+It is used to save from needing to pass data as props through intermediate components (aka** prop drilling**).
+This function creates a new context object that can be used with [useContext](/reference/component-apis/use-context) and offers the Provider control flow.
+The default value is used when no Provider is found above in the hierarchy.
+
+## Usage
+
+To avoid reinstatiating a new context when Hot-Module Replacement (HMR) occurs, it is recommended to use `createContext` in its own module (file).
+
+
+When using HMR, the context is lost when the module is reloaded. Which will cause an error to be thrown as `useContext` will try to access it while it is still reloading.
+
+
+
+For example:
+
+```ts title="/context/counter.ts"
+import { createContext } from "solid-js";
+
+export const INITIAL_COUNT = 0;
+
+const INITIAL_STORE_SETTER = {
+ increment: () => {},
+ decrement: () => {}
+};
+
+export const CounterContext = createContext([
+ { count: INITIAL_COUNT },
+ INITIAL_STORE_SETTER
+]);
+```
+
+With the context created in its own module, you can use to instantiate the context provider.
+
+```ts title="/context/counter-component.tsx"
+import { createStore } from 'solid-js/store';
+import { CounterContext, INITIAL_COUNT } from "./counter.ts";
+
+export function CounterProvider(props) {
+ const [value, setValue] = createStore({ count: props.initialCount || INITIAL_COUNT })
+
+ const counter = [
+ value,
+ {
+ increment() {
+ setValue("count", currentCount => currentCount + 1)
+ },
+ decrement() {
+ setValue("count", currentCount => currentCount - 1)
+ },
+ },
+ ]
+
+ return (
+
+ {props.children}
+
+ )
+}
+```
+
+A few imporant notes on how to pass data through the context API:
+
+- The value passed to provider is passed to `useContext` as is.
+- Wrapping as a reactive expression will not work.
+- You should pass in Signals and Stores directly instead of accessing them in the JSX.
+
+To learn how to consume the context, see the [useContext](/reference/component-apis/use-context) documentation and the [Context concepts entry](/concepts/context).
+
+## Default Values
+
+`createContext()` takes an optional "default value" as an argument.
+If `useContext` is called and there is no corresponding context provider above it in the component hierarchy, then the value passed as `defaultValue` is returned.
+
+However, if no `defaultValue` was passed, then `undefined` is returned in this case.
+Also, `defaultValue` (or `undefined`) is returned if `useContext` is called inside an event callback, as it is then outside of the component hierarchy.
+
+This has implications for TS.
+If no `defaultValue` is passed, then it is possible that `useContext()` will return `undefined`, and the types reflect this.
+
+Another (used in the example in the previous section) is provide a default value to `createContext()`.
+In that case, `useContext()` will always return a value, and therefore TS will not complain either.
+The pitfall with this approach is that if you _unintentionally_ use `useContext` outside of a provider, it may not be immediately apparent, because the context is still providing a valid value.
+Therefore, if you expect to always use `useContext` within a provider, it is best to use the error based approach described above.
+
+## Type signature
+
+```ts
+interface Context {
+ id: symbol
+ Provider: (props: { value: T; children: any }) => any
+ defaultValue: T
+}
+
+function createContext(defaultValue?: T): Context
+```
+
+
+---
+title: createUniqueId
+---
+
+```ts
+import { createUniqueId } from "solid-js"
+
+function createUniqueId(): string
+
+```
+
+A universal id generator that is stable across server/browser.
+
+```ts
+const id = createUniqueId()
+```
+
+**Note:** on the server this only works under hydratable components.
+
+
+---
+title: lazy
+---
+
+```ts
+import { lazy } from "solid-js"
+import type { Component } from "solid-js"
+
+function lazy>(
+ fn: () => Promise<{ default: T }>
+): T & { preload: () => Promise }
+```
+
+Used to lazy load components to allow for code splitting.
+Components are not loaded until rendered.
+Lazy loaded components can be used the same as its statically imported counterpart, receiving props etc.
+Lazy components trigger ``
+
+```tsx
+// wrap import
+const ComponentA = lazy(() => import("./ComponentA"));
+
+// use in JSX
+
+```
+
+
+---
+title: useContext
+---
+
+Used to grab context within a context provider scope to allow for deep passing of props without having to pass them through each Component function.
+It's therefore used in conjunction with [`createContext`](/reference/component-apis/create-context) to consume the data from a Provider scope and thus avoid passing data through intermediate components (prop drilling).
+
+```ts
+const [state, { increment, decrement }] = useContext(CounterContext)
+```
+
+## Recommended usage
+
+It is often a good idea to wrap `useContext` in a function like so:
+
+```ts title="/context/counter-component.tsx"
+function useCounterContext() {
+ const context = useContext(CounterContext)
+
+ if (!context) {
+ throw new Error("useCounterContext: cannot find a CounterContext")
+ }
+
+ return context
+}
+```
+
+See the API reference of [createContext](/reference/component-apis/create-context) the API on how to generate a Provider scope.
+And check the [Context concepts](/concepts/context) for more information on how to architecture your contexts.
+
+## Type signature
+
+```ts
+import { type Context } from "solid-js"
+
+function useContext(context: Context): T
+
+```
+
+---
+title:
+order: 5
+---
+
+This component lets you insert an arbitrary Component or tag and passes the props through to it.
+
+```tsx
+import { Dynamic } from "solid-js/web"
+import type { JSX } from "solid-js"
+
+function Dynamic(
+ props: T & {
+ children?: any
+ component?: Component | string | keyof JSX.IntrinsicElements
+ }
+): () => JSX.Element
+```
+
+Here's an example of how you can use it:
+
+```tsx
+
+```
+
+## Props
+
+| Name | Type | Description |
+| :---------- | :---------------------------------------------------------- | :---------------------------------------- |
+| `component` | `Component` \| `string` \| `keyof JSX.IntrinsicElements` | The component to render. |
+| `children` | `any` | The children to pass to the component. |
+| `...` | `T` | Any other props to pass to the component. |
+
+
+---
+title:
+order: 5
+---
+
+Catches uncaught errors and renders fallback content.
+
+```tsx
+import { ErrorBoundary } from "solid-js"
+import type { JSX } from "solid-js"
+
+function ErrorBoundary(props: {
+ fallback: JSX.Element | ((err: any, reset: () => void) => JSX.Element)
+ children: JSX.Element
+}): () => JSX.Element
+```
+
+Here's an example of how to use it:
+
+```tsx
+Something went terribly wrong
}>
+
+
+```
+
+If you want to customize the error message, you can pass a function as the `fallback` prop. The function will be called with the error and a `reset` function. The `reset` function will reset the error boundary and re-render the children.
+
+```tsx
+
Error: {err.toString()}
}
+>
+
+
+```
+
+## Props
+
+| Name | Type | Description |
+| :--------- | :-------------------------------------------------------------- | :------------------------------------------------------ |
+| `fallback` | `JSX.Element \| ((err: any, reset: () => void) => JSX.Element)` | The fallback content to render when an error is caught. |
+
+
+---
+title:
+order: 5
+---
+
+The `` component is used to render a list of items. It is similar to the `.map()` function in JavaScript.
+
+```ts
+import { For } from "solid-js"
+import type { JSX } from "solid-js"
+
+function For(props: {
+ each: readonly T[]
+ fallback?: JSX.Element
+ children: (item: T, index: () => number) => U
+}): () => U[]
+```
+
+A referentially keyed loop with efficient updating of only changed items. The callback takes the current item as the first argument:
+
+```jsx
+Loading...
}>
+ {(item) =>
{item}
}
+
+```
+
+The `each` prop can also be a function that returns a list. This is useful for creating a loop that depends on a state value:
+
+```jsx
+{(item) =>
{item}
}
+```
+
+The optional second argument is an index signal:
+
+```jsx
+Loading...}>
+ {(item, index) => (
+
+ #{index()} {item}
+
+ )}
+
+```
+
+## Props
+
+| Name | Type | Description |
+| :--------- | :------------------------------------ | :--------------------------------------------------------------- |
+| `each` | `readonly T[]` | The list of items to render. |
+| `fallback` | `JSX.Element` | A fallback element to render while the list is loading. |
+| `children` | `(item: T, index: () => number) => U` | A callback that returns a JSX element for each item in the list. |
+
+
+---
+title:
+---
+
+Non-keyed list iteration (rendered nodes are keyed to an array index). This is useful when there is no conceptual key, like if the data consists of primitives and it is the index that is fixed rather than the value.
+
+```ts
+import { Index } from "solid-js"
+import type { JSX } from "solid-js"
+
+function Index(props: {
+ each: readonly T[];
+ fallback?: JSX.Element;
+ children: (item: () => T, index: number) => U;
+}): () => U[];
+```
+
+A super simple implementation of this component might look like this:
+
+```tsx
+function Index(props: {
+ each: readonly T[];
+ fallback?: JSX.Element;
+ children: (item: () => T, index: number) => U;
+}) {
+ return () => {
+ const [items, setItems] = createSignal(props.each);
+ return props.each.map((_, i) => props.children(() => items()[i], i));
+ };
+}
+```
+
+Here's a look at the implementation of the `Index` component in Solid:
+
+```tsx
+Loading...}>
+ {(item) =>
{item()}
}
+
+```
+
+Notice that the item is a signal unlike the `For` component. This is because the `Index` component is not keyed to the item itself but rather the index.
+
+Optional second argument is an index number:
+
+```tsx
+Loading...}>
+ {(item, index) => (
+
+ #{index} {item()}
+
+ )}
+
+```
+
+## Props
+
+| Name | Type | Description |
+| :------- | :------------------------------------ | :-------------------------------------------------------------- |
+| each | `readonly T[]` | The array to iterate over. |
+| fallback | `JSX.Element` | Optional fallback element to render while the array is loading. |
+| children | `(item: () => T, index: number) => U` | The function that renders the children. |
+
+---
+title:
+---
+
+`` is a component that allows you to render children into a DOM node that exists outside the DOM hierarchy of the parent component.
+
+This is useful when your UI has some elements that need to appear on top of everything else, such as modals and tooltips.
+
+```tsx
+import { Portal } from "solid-js/web"
+import type { JSX } from "solid-js"
+
+function Portal(props: {
+ mount?: Node
+ useShadow?: boolean
+ isSVG?: boolean
+ children: JSX.Element
+}): Text
+```
+
+This inserts the element in the mount node.
+Useful for inserting Modals outside of the page layout.
+Events still propagate through the component hierarchy, however `` will only run on the client and has hydration _disabled_.
+
+The portal is mounted in a `
` unless the target is the document head.
+`useShadow` places the element in a Shadow Root for style isolation, and `isSVG` is required if inserting into an SVG element so that the `
` is not inserted.
+
+```tsx
+
+
My Content
+
+```
+
+## Props
+
+| Name | Type | Default | Description |
+| :---------- | :-------- | :------------ | :------------------------------------------------ |
+| `mount` | `Node` | document.body | The DOM node to mount the portal in. |
+| `useShadow` | `boolean` | false | Whether to use a Shadow Root for style isolation. |
+| `isSVG` | `boolean` | false | Whether the mount node is an SVG element. |
+
+
+---
+title:
+order: 5
+---
+
+The `Show` control flow is used to conditionally render part of the view: it renders children when `when` is truthy, a fallback otherwise. It is similar to the ternary operator `(when ? children : fallback)` but is ideal for templating JSX.
+
+```ts
+import { Show } from "solid-js"
+import type { JSX } from "solid-js"
+
+function Show(props: {
+ when: T | undefined | null | false
+ keyed?: boolean
+ fallback?: JSX.Element
+ children: JSX.Element | ((item: T | Accessor) => JSX.Element)
+}): () => JSX.Element
+```
+
+Here's an example of using the `Show` control flow:
+
+```tsx
+ 0} fallback={
Loading...
}>
+
My Content
+
+```
+
+`Show` can also be used as a way of keying blocks to a specific data model. For example the function is re-executed whenever the user model is replaced.
+
+```tsx
+Loading...
} keyed>
+ {(user) =>
{user.firstName}
}
+
+```
+
+If the `keyed` property is not used, the argument of the child function will be an accessor containing the item.
+
+```tsx
+Loading...
}>
+ {(user) =>
{user().firstName}
}
+
+```
+
+## Props
+
+| Name | Type | Description |
+| :--------- | :-------------------------------- | :-------------------------------------------- |
+| `when` | `T \| undefined \| null \| false` | The value to test for truthiness |
+| `keyed` | `boolean` | Whether to key the block to the value of when |
+| `fallback` | `JSX.Element` | The fallback to render when the `when` is falsy |
+
+
+---
+title:
+order: 5
+---
+
+SuspenseList allows for coordinating multiple parallel Suspense and SuspenseList components. It controls the order in which content is revealed to reduce layout thrashing and has an option to collapse or hide fallback states.
+
+```ts
+import { SuspenseList } from "solid-js"
+import type { JSX } from "solid-js"
+
+function SuspenseList(props: {
+ children: JSX.Element
+ revealOrder: "forwards" | "backwards" | "together"
+ tail?: "collapsed" | "hidden"
+}): JSX.Element
+```
+
+**Note**: SuspenseList is still in the experimental stage and does not have full `SSR` support.
+
+Here's an example of how to use SuspenseList:
+
+```tsx
+
+
+ Loading posts...}>
+
+
+ Loading fun facts...}>
+
+
+
+```
+
+## Props
+
+| Name | Type | Default | Description |
+| ------------- | ----------------------------------------- | ------------ | --------------------------------------------------------------------------- |
+| `revealOrder` | `"forwards" \| "backwards" \| "together"` | `"forwards"` | Determines the order in which the SuspenseList children should be revealed. |
+| `tail` | `"collapsed" \| "hidden"` | `undefined` | TODO |
+
+### `revealOrder`
+
+`"forwards" | "backwards" | "together"`
+
+- `"forwards"`: Reveals each item in the list once the previous item has finished rendering. This is the default.
+- `"backwards"`: Reveals each item in the list once the next item has finished rendering.
+- `"together"`: Reveals all items in the list at the same time.
+
+### `tail`
+
+`"collapsed" | "hidden"`
+
+
+---
+title:
+order: 5
+---
+
+A component that tracks all resources read under it and shows a fallback placeholder state until they are resolved. What makes `Suspense` different than `Show` is that it is non-blocking in the sense that both branches exist at the same time even if not currently in the DOM. This means that the fallback can be rendered while the children are loading. This is useful for loading states and other asynchronous operations.
+
+```tsx
+import { Suspense } from "solid-js"
+import type { JSX } from "solid-js"
+
+function Suspense(props: {
+ fallback?: JSX.Element
+ children: JSX.Element
+}): JSX.Element
+
+```
+
+Here's an example of a `Suspense` component that shows a loading spinner while the `User` component is loading.
+
+```tsx
+}>
+
+
+
+```
+
+## Nested Suspense
+
+`` is triggered whenever a resource is read under the suspense boundary, and waits until all resources read
+under the suspense boundary have resolved. Often, however, you may not want this behavior. For example, if your entire page is
+wrapped in suspense, you may not want a resource that only populates a certain part of the page to trigger suspense.
+In that case, you can wrap that resource usage in its own suspense boundary, and the resource will only trigger the
+closest suspense boundary.
+
+For example, in the code below, only the `title()` resource will trigger the top level suspense boundary, and only the `data()`
+resource will trigger the nested suspense boundary:
+
+```jsx
+const MyComponent = () => {
+ const [title] = createResource(async () => { /* fetcher code here */ })
+ const [data] = createResource(async () => { /* fetcher code here */ })
+
+
{title()}
+
+ {data()}
+
+
+}
+
+```
+
+## The purpose of {""}
+
+To understand the purpose of suspense, let's consider the following code snippets. These snippets will have some drawbacks which we will solve by using suspense. We will also see how it is possible to use `Suspense` yet not reap its benefits.
+
+Our example use case is to display a user profile. A naive snippet would look like this:
+
+```jsx
+const MyComponentWithOptionalChaining = () => {
+ const [profile] = createResource(async () => {
+ /* fetcher code here */
+ })
+ return (
+ <>
+
{profile()?.name}
+
{profile()?.email}
+ >
+ )
+}
+
+```
+
+In this code, `profile()` starts as `undefined`, and when the fetcher code finishes, resolves to an object with `name` and `email` properties. Although the resource has not resolved yet, the two `div`s are already created and attached to the document body, albeit with empty text nodes. Once the resource resolves, the `div`s are updated with the appropriate data.
+
+The downside of this approach is that the user is shown an empty component - let's see if we can do better than that in this next snippet:
+
+```jsx
+const MyComponentWithShow = () => {
+ const [profile] = createResource(async () => {
+ /* fetcher code here */
+ })
+ return (
+ fetching user data}>
+
{profile().name}
+
{profile().email}
+
+ )
+}
+
+```
+
+In this snippet, we first show a fallback when the resource hasn't resolved yet, and then switch to showing the profile data once it has. This results in a better user experience.
+
+On the other hand, there is a slight downside to this approach. In our first example (using optional chaining), the divs were created immediately, and once the resource resolves all that is needed to be done is to fill in the text of the `div`s. But in our second example (using ``), the `div`s are only created once the resource has resolved, which means there is more work that needs to be done after the resource has resolved before the data can be shown to the user (of course, in this toy example the amount of DOM work is relatively trivial).
+
+We can have the best of both worlds by using {""}:
+
+```jsx
+const MyComponentWithSuspense = () => {
+ const [profile] = createResource(async () => {
+ /* fetcher code here */
+ })
+ return (
+ fetching user data}>
+
{profile()?.name}
+
{profile()?.email}
+
+ )
+}
+```
+
+In this case, the `div`s are created immediately, but instead of being attached to the document body, the fallback is shown. Once the resource resolves, the text in the `div`s is updated, and then they are attached to the document (and the fallback removed).
+
+It is important to note that _the execution of the component does not pause_ when using suspense. Instead, when a resource is read under a suspense boundary, it ensures that the nodes are not attached to the document until after the resource has resolved. Suspense allows us to have the best of both worlds: do as much work as we can _before_ the resource resolves, and also show a fallback until then.
+
+With this in mind, we can understand that there isn't much gained from suspense in the following code:
+
+```jsx
+const MyComponentWithSuspenseAndShow = () => {
+ const [profile] = createResource(async () => {
+ /* fetcher code here */
+ })
+ return (
+ fetching user data}>
+
+
{profile().name}
+
{profile().email}
+
+
+ )
+}
+```
+
+In this code, we don't create _any_ DOM nodes inside {""} before the resource resolves, so it is pretty much the same as the second example where we only used ``.
+
+
+ Suspense is triggered by reading a resource inside the {""}{" "}
+ boundary. Components wrapped with suspense still run fully, just as they would
+ without suspense. However, code wrapped in `onMount` and `createEffect` only
+ run after the resource resolves.
+
+
+## Props
+
+| Name | Type | Description |
+| :--------- | :------------ | :--------------------------------------------------------------- |
+| `fallback` | `JSX.Element` | The fallback component to render while the children are loading. |
+
+
+---
+title: /
+order: 5
+---
+
+Useful for when there are more than 2 mutual exclusive conditions. It is a more flexible version of the if-else-if-else-if-else-... chain.
+
+```ts
+import { Switch, Match } from "solid-js"
+import type { MatchProps, JSX } from "solid-js"
+
+function Switch(props: {
+ fallback?: JSX.Element
+ children: JSX.Element
+}): () => JSX.Element
+
+type MatchProps = {
+ when: T | undefined | null | false
+ children: JSX.Element | ((item: T) => JSX.Element)
+}
+function Match(props: MatchProps)
+```
+
+A super simple implementation of this component would be:
+
+```tsx
+function Switch(props) {
+ let children = props.children
+
+ if (!Array.isArray(children)) children = [children]
+
+ for (let i = 0; i < children.length; i++) {
+ const child = children[i]
+ if (child.props.when) return child
+ }
+
+ return props.fallback
+}
+```
+
+For example, it can be used to perform basic routing:
+
+```tsx
+Not Found}>
+
+
+
+
+
+
+
+```
+
+Match also supports function children to serve as keyed flow.
+
+## Props
+
+### Switch
+
+| Name | Type | Default | Description |
+| ---------- | ------------- | ----------- | -------------------------------------------------------------------------------- |
+| `fallback` | `JSX.Element` | `undefined` | The fallback element to render if no `Match` component has a truthy `when` prop. |
+
+### Match
+
+| Name | Type | Default | Description |
+| ------ | --------------------------------- | ----------- | ------------------------------------------------------------------------- |
+| `when` | `T \| undefined \| null \| false` | `undefined` | The condition to check. If it is truthy, the `children` will be rendered. |
+
+
+---
+title: attr:*
+---
+
+Forces the prop to be treated as an attribute instead of a property.
+Useful for Web Components where you want to set attributes.
+
+```tsx
+
+```
+
+
+ Type definitions are required when using TypeScript.
+ See the[TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes) page for examples.
+
+
+
+---
+title: bool:*
+---
+
+`bool:*` controls the presence of an attribute in an element.
+When the value is `truthy` it adds the `attribute` to the element.
+Alternatively, when the value is `falsy` it removes the `attribute` from the element.
+This attribute is most useful for Web Components.
+
+```tsx
+
+```
+
+```tsx
+// Assuming `prop.value` is `truthy`, then it becomes
+
+
+// And when `falsy`, then it becomes
+
+
+```
+
+
+ Type definitions are required when using TypeScript.
+ See the [TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes) page for examples.
+
+
+
+---
+title: classList
+order: 1
+---
+
+Solid offers two ways to set the class of an element: class and classList attributes.
+
+First, you can set class=... like any other attribute. For example:
+
+```tsx
+// Two static classes
+
+
+// One dynamic class, deleting class attribute if it's not needed
+
+
+// Two dynamic classes
+
+```
+
+
+ Note that className was deprecated in Solid 1.4 in favor of{" "}
+ class.
+
+
+Alternatively, the `classList` pseudo-attribute lets you specify an object, where each key is a class and the value is treated as a boolean representing whether to include that class. For example (matching the last example):
+
+```tsx
+
+```
+
+This example compiles to a render effect that dynamically calls [element.classList.toggle](https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle) to turn each class on or off, only when the corresponding boolean changes. For example, when `state.active` becomes true [false], the element gains [loses] the `active` class.
+
+The value passed into `classList` can be any expression (including a signal getter) that evaluates to an appropriate object. Some examples:
+
+```tsx
+// Dynamic class name and value
+;
+
+// Signal class list
+const [classes, setClasses] = createSignal({})
+setClasses((c) => ({ ...c, active: true }))
+;
+```
+
+It's also possible, but dangerous, to mix class and classList. The main safe situation is when class is set to a static string (or nothing), and classList is reactive. (class could also be set to a static computed value as in `class={baseClass()}`, but then it should appear before any classList pseudo-attributes.) If both class and classList are reactive, you can get unexpected behavior: when the class value changes, Solid sets the entire class attribute, so will overwrite any toggles made by classList.
+
+Because classList is a compile-time pseudo-attribute, it does not work in a prop spread like `` or in ``.
+
+
+---
+title: innerHTML or textContent
+order: 2
+---
+
+These work the same as their property equivalent. Set a string and they will be set. **Be careful!!** Setting `innerHTML` with any data that could be exposed to an end user as it could be a vector for malicious attack. `textContent` while generally not needed is actually a performance optimization when you know the children will only be text as it bypasses the generic diffing routine.
+
+```tsx
+
+```
+
+
+---
+title: on:*
+order: 4
+---
+
+For events with capital letters, listener options, or if you need to attach event handlers directly to a DOM element instead of optimized delegating via the document, use `on:*` in place of `on*`.
+
+```tsx
+
console.log("Welcome!")} />
+```
+
+This directly attaches an event handler (via [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)) to the `div`.
+
+New in v1.9.0
+
+An aditional special syntax that allows full control of [`capture`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#capture), [`passive`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#passive), [`once`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#once) and [`signal`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#signal) is an intersection or combination of `EventListenerObject` & `AddEventListenerOptions`, as follows:
+
+```tsx
+const handler = {
+ handleEvent(e) {
+ console.log(e)
+ },
+ once:true,
+ passive:false,
+ capture:true
+}
+
+
+
+// or inline
+
+
+```
+
+This new syntax replaces the now deprecated `oncapture:` and it's future proof for any posible new event listener options.
+
+
+---
+title: on*
+order: 3
+---
+
+Event handlers in Solid typically take the form of `onclick` or `onClick` depending on style.
+
+```tsx
+
console.log(e.currentTarget)} />
+```
+
+Conceptually, this example attaches a `click` event listener (via [`addEventListener`](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)) to the `div`. However, Solid actually handles common UI events that bubble and are composed (such as `click`) at the document level, and then synthetically implements delegation (capturing and bubbling). This improves performance for these common events by reducing the number of event handlers.
+
+Note that `onClick` handles the event `click`; in general, event names get mapped to lower case. If you need to work with event names containing capital letters, or use listener options such once, passive, capture see [`on:`](/reference/jsx-attributes/on) which attaches event handlers directly (also avoiding fancy delegation via document).
+
+Solid also supports passing a two-element array to the event handler to bind a value to the first argument of the event handler. This doesn't use `bind` or create an additional closure, so it is a highly optimized way of delegating events.
+
+```tsx
+function handler(itemId, e) {
+ /*...*/
+}
+
+
+ {(item) => }
+
;
+```
+
+Events are never rebound and the bindings are not reactive, as it is expensive to attach and detach listeners. Since event handlers are called like any other function each time an event fires, there is no need for reactivity; shortcut your handler if desired.
+
+```tsx
+// if defined, call it; otherwise don't.
+
props.handleClick?.()} />
+```
+
+Note that `onChange` and `onInput` work according to their native behavior (unlike, say, React). [`onInput`](https://developer.mozilla.org/en-US/docs/Web/API/Element/input_event) will fire immediately after the value has changed; for most `` fields, [`onChange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event) will only fire after the field loses focus. The event's `currentTarget` refers to the element that the event was attached to, while `target` gives the element that actually triggered the event (e.g. the user clicked on).
+
+
+---
+title: "@once"
+order: 5
+---
+
+Solid's compiler uses a heuristic for reactive wrapping and lazy evaluation of JSX expressions. Does it contain a function call, a property access, or JSX? If yes we wrap it in a getter when passed to components or in an effect if passed to native elements.
+
+Knowing this heuristic and its limitations, we can reduce overhead of things we know will never change by accessing them outside of the JSX. A lone variable will never be wrapped. We can also tell the compiler not to wrap them by starting the expression with a comment decorator `/* @once */`.
+
+```tsx
+
+```
+
+This also works on children.
+
+```tsx
+{/*@once*/ state.wontUpdate}
+```
+
+
+---
+title: prop:*
+order: 6
+---
+
+Forces the prop to be treated as a property instead of an attribute.
+
+```tsx
+
+```
+
+
+ Type definitions are required when using TypeScript.
+ See the [TypeScript](/configuration/typescript#forcing-properties-and-custom-attributes) page for examples.
+
+
+---
+title: ref
+order: 7
+---
+
+Refs are a way of getting access to underlying DOM elements in our JSX. While it is true one could just assign an element to a variable, it is more optimal to leave components in the flow of JSX. Refs are assigned at render time but before the elements are connected to the DOM. They come in 2 flavors.
+
+```tsx
+// variable assigned directly by ref
+let myDiv;
+
+// use onMount or createEffect to read after connected to the DOM
+onMount(() => console.log(myDiv));
+
+
+
+// Or, callback function (called before connected to the DOM)
+
console.log(el)} />
+```
+
+Refs can also be used on Components. They still need to be attached on the other side.
+
+```tsx
+function MyComp(props) {
+ return
+}
+
+function App() {
+ let myDiv
+ onMount(() => console.log(myDiv.clientWidth))
+ return
+}
+```
+
+
+---
+title: style
+order: 7
+---
+
+Solid's style attribute lets you provide either a CSS string or an object where keys are CSS property names:
+
+```tsx
+// string
+
+
+// object
+
+```
+
+Unlike [React's style attribute](https://reactjs.org/docs/dom-elements.html#style), Solid uses **element.style.setProperty** under the hood. This means you need to use the lower-case, dash-separated version of property names instead of the JavaScript camel-cased version, such as `background-color` rather than `backgroundColor`. This actually leads to better performance and consistency with SSR output.
+
+```tsx
+// string
+
+
+// object
+
+```
+
+This also means you can set CSS variables! For example:
+
+```tsx
+// set css variable
+
+```
+
+
+---
+title: use:*
+order: 5
+---
+
+These are custom directives. In a sense this is just syntax sugar over ref but allows us to easily attach multiple directives to a single element. A directive is a function with the following signature:
+
+```ts
+function directive(element: Element, accessor: () => any): void
+```
+
+Directive functions are called at render time but before being added to the DOM. You can do whatever you'd like in them including create signals, effects, register clean-up etc.
+
+```tsx
+const [name, setName] = createSignal("")
+
+function model(el, value) {
+ const [field, setField] = value()
+ createRenderEffect(() => (el.value = field()))
+ el.addEventListener("input", (e) => setField(e.target.value))
+};
+
+
+```
+
+To register with TypeScript extend the JSX namespace.
+
+```ts
+declare module "solid-js" {
+ namespace JSX {
+ interface Directives {
+ model: [() => any, (v: any) => any]
+ }
+ }
+}
+```
+
+
+Directives only work with native HTML elements (HTML/SVG/MathML/Custom Elements).
+Directives are not forwarded and **won't work in user defined components**, such as `` [see also](https://github.com/solidjs/solid/discussions/722)
+
+
+
+---
+title: onCleanup
+order: 5
+---
+
+`onCleanup` registers a cleanup method that executes on disposal and recalculation of the current reactive scope.
+Can be used anywhere to clean up any side effects left behind by initialization.
+
+When used in a Component, it runs when the component is unmounted.
+When used in reactive contexts, such [`createEffect`](/reference/basic-reactivity/create-effect), [`createMemo`](/reference/basic-reactivity/create-memo) or a [`createRoot`](/reference/reactive-utilities/create-root), it runs when the reactive scope is disposed or refreshed.
+
+```ts
+import { onCleanup } from "solid-js"
+
+function onCleanup(fn: () => void): void;
+```
+
+Without the `onCleanup` function, the event listener would remain attached to the `document` even after the component is removed from the page.
+This can cause memory leaks and other issues.
+
+```tsx
+import { createSignal, onCleanup } from "solid-js"
+
+const Component = () => {
+ const [count, setCount] = createSignal(0);
+
+ const handleClick = () => setCount((value) => value + 1);
+
+ document.addEventListener("click", handleClick);
+
+ /**
+ * Remove the event listener when the component is removed/unmounted from the page.
+ */
+ onCleanup(() => {
+ document.removeEventListener("click", handleClick);
+ });
+
+ return Document has been clicked {count()} times;
+};
+```
+
+
+---
+title: onMount
+order: 5
+---
+
+Registers a method that runs after initial rendering is done and the elements are mounted to the page.
+Ideal for using [refs](/reference/jsx-attributes/ref) and managing other one-time setup.
+
+```tsx
+import { onMount } from "solid-js"
+
+function onMount(fn: () => void): void
+
+```
+
+This is an alias for an effect that is non-tracking, meaning that it is equivalent to a [`createEffect`](/reference/basic-reactivity/create-effect) with no dependencies.
+
+```tsx
+// example that shows how to use onMount to get a reference to an element
+import { onMount } from "solid-js"
+
+function MyComponent() {
+ let ref: HTMLButtonElement
+
+ // when the component is mounted, the button will be disabled
+ onMount(() => {
+ ref.disabled = true
+ })
+ return
+}
+```
+
+
+---
+title: batch
+---
+
+```ts
+import { batch } from "solid-js"
+
+function batch(fn: () => T): T
+```
+
+`batch` is a low-level API that batches updates together.
+More precisely, `batch(fn)` holds the execution of downstream computations
+during the `fn` block, executing them all together once the block `fn` returns.
+Thus, instead of a downstream computation executing after every dependency
+update, it will update just once at the end of the batch.
+
+Batching improves performance by avoiding unnecessary recalculation.
+Suppose you have a downstream memo `down` that depends on
+multiple upstream signals `up1`, `up2`, and `up3`:
+
+```ts
+import { createSignal, createMemo, createEffect } from "solid-js"
+const [up1, setUp1] = createSignal(1)
+const [up2, setUp2] = createSignal(2)
+const [up3, setUp3] = createSignal(3)
+const down = createMemo(() => up1() + up2() + up3())
+// For illustration, monitor when `down` gets recomputed:
+createEffect(() => console.log(down())) // outputs 6
+```
+
+If you directly update all of the upstream signals outside of batch mode,
+then `down` will recompute every time.
+
+```ts
+setUp1(4) // recomputes down, outputs 9
+setUp2(5) // recomputes down, outputs 12
+setUp3(6) // recomputes down, outputs 15
+```
+
+If instead you update the upstream signals within a `batch`, then `down`
+will update only once at the end:
+
+```ts
+batch(() => {
+ setUp1(10) // doesn't update down yet
+ setUp2(10) // doesn't update down yet
+ setUp3(10) // doesn't update down yet
+}) // recomputes down, outputs 30
+```
+
+The impact is even more dramatic if you have *m* downstream computations
+(memos, effects, etc.) that each depend on *n* upstream signals.
+Without batching, modifying all *n* upstream signals
+would cause *m n* updates to the downstream computations.
+With batching, modifying all *n* upstream signals
+would cause *m* updates to the downstream computations.
+Given that each update takes at least *n* time
+(just to read the upstream signals), this cost savings can be significant.
+Batching is also especially helpful when the downstream effects include
+DOM updates, which can be expensive.
+
+Solid uses `batch` internally to automatically batch updates for you
+in a few cases:
+
+* Within [`createEffect`](/reference/basic-reactivity/create-effect)
+ and [`onMount`](/reference/lifecycle/on-mount)
+ (unless they are outside a [root](/reference/reactive-utilities/create-root))
+* Within the [setter of a store](/reference/store-utilities/create-store#setter)
+ (which can update several properties at once)
+* Within array methods (e.g. `Array.prototype.splice`) of a
+ [mutable store](/reference/store-utilities/create-mutable)
+ (which can update several elements at once)
+
+These save you from having to use `batch` yourself in many cases.
+For the most part, automatic batching should be transparent to you,
+because accessing a signal or memo will cause it to update if it is out of date
+(as of Solid 1.4). For example:
+
+```ts
+batch(() => {
+ setUp1(11) // doesn't update down yet
+ setUp2(11) // doesn't update down yet
+ setUp3(11) // doesn't update down yet
+ console.log(down()) // recomputes down, outputs 33
+ setUp1(12) // doesn't update down yet
+ setUp2(12) // doesn't update down yet
+ setUp3(12) // doesn't update down yet
+}) // recomputes down, outputs 36
+```
+
+You can think of `batch(fn)` as setting a global "batch mode" variable,
+calling the function `fn`, and then restoring the global variable to its
+previous value.
+This means that you can nest `batch` calls, and they will form one big batch.
+It also means that, if `fn` is asynchronous,
+only the updates before the first `await` will be batched.
+
+
+---
+title: catchError
+---
+
+
+New in v1.7.0
+
+
+```tsx
+import { catchError } from "solid-js"
+
+function catchError(tryFn: () => T, onError: (err: any) => void): T
+```
+
+Wraps a `tryFn` with an error handler that fires if an error occurs below that point.
+Only the nearest scope error handlers execute.
+Rethrow to trigger up the line.
+
+---
+title: createRoot
+---
+
+```ts
+import { createRoot } from "solid-js"
+
+function createRoot(fn: (dispose: () => void) => T): T
+
+```
+
+Creates a new non-tracked owner scope that doesn't auto-dispose.
+This is useful for nested reactive scopes that you do not wish to release when the parent re-evaluates.
+
+All Solid code should be wrapped in one of these top level as they ensure that all memory/computations are freed up.
+Normally you do not need to worry about this as createRoot is embedded into all render entry functions.
+
+
+---
+title: from
+---
+
+```tsx
+import { from } from "solid-js"
+
+function from(
+ producer:
+ | ((setter: (v: T) => T) => () => void)
+ | {
+ subscribe: (
+ fn: (v: T) => void
+ ) => (() => void) | { unsubscribe: () => void }
+ }
+): () => T | undefined
+
+```
+
+A helper to make it easier to interop with external producers like RxJS observables or with Svelte Stores.
+This basically turns any subscribable (object with a subscribe method) into a Signal and manages subscription and disposal.
+
+```tsx
+const signal = from(obsv$)
+```
+
+It can also take a custom producer function where the function is passed a setter function that returns an unsubscribe function:
+
+```tsx
+const clock = from((set) => {
+ const interval = setInterval(() => {
+ set((v) => v + 1)
+ }, 1000)
+
+ return () => clearInterval(interval)
+})
+```
+
+## Arguments
+
+| Name | Type | Description |
+| :------- | :----------------------------------------------------------------------------------------------------------------------------- | :------------------------------------------- |
+| producer | `((setter: (v: T) => T) => () => void) \| { subscribe: (fn: (v: T) => void) => (() => void) \| { unsubscribe: () => void }; }` | The producer function or subscribable object |
+
+
+---
+title: getOwner
+---
+
+```tsx
+import { getOwner } from "solid-js"
+import type { Owner } from "solid-js"
+
+function getOwner(): Owner
+
+```
+
+Gets the reactive scope that owns the currently running code, e.g., for passing into a later call to `runWithOwner` outside of the current scope.
+
+Internally, computations (effects, memos, etc.) create owners which are children of their owner, all the way up to the root owner created by `createRoot` or `render`.
+In particular, this ownership tree lets Solid automatically clean up a disposed computation by traversing its subtree and calling all `onCleanup` callbacks.
+For example, when a createEffect's dependencies change, the effect calls all descendant `onCleanup` callbacks before running the effect function again.
+Calling `getOwner` returns the current owner node that is responsible for disposal of the current execution block.
+
+Components are not computations, so do not create an owner node, but they are typically rendered from a `createEffect` which does, so the result is similar: when a component gets unmounted, all descendant `onCleanup` callbacks get called.
+Calling `getOwner` from a component scope returns the owner that is responsible for rendering and unmounting that component.
+
+Note that the owning reactive scope isn't necessarily tracking.
+For example, untrack turns off tracking for the duration of a function (without creating a new reactive scope), as do components created via JSX (``).
+
+
+---
+title: indexArray
+---
+
+```tsx
+import { indexArray } from "solid-js"
+
+function indexArray(
+ list: () => readonly T[],
+ mapFn: (v: () => T, i: number) => U
+): () => U[]
+
+```
+
+Similar to `mapArray` except it maps by index.
+The item is a signal and the index is now the constant.
+
+Underlying helper for the `` control flow.
+
+```tsx
+const mapped = indexArray(source, (model) => {
+ return {
+ get id() {
+ return model().id
+ }
+ get firstInitial() {
+ return model().firstName[0];
+ },
+ get fullName() {
+ return `${model().firstName} ${model().lastName}`;
+ },
+ }
+});
+```
+
+## Arguments
+
+| Name | Type | Description |
+| :---- | :----------------------------- | :-------------------- |
+| list | `() => readonly T[]` | The list to map. |
+| mapFn | `(v: () => T, i: number) => U` | The mapping function. |
+
+
+---
+title: mapArray
+---
+
+```ts
+import { mapArray } from "solid-js"
+
+function mapArray(
+ list: () => readonly T[],
+ mapFn: (v: T, i: () => number) => U
+): () => U[]
+
+```
+
+Reactive map helper that caches each item by reference to reduce unnecessary mapping on updates.
+It only runs the mapping function once per value and then moves or removes it as needed.
+The index argument is a signal. The map function itself is not tracking.
+
+Underlying helper for the `` control flow.
+
+```ts
+const mapped = mapArray(source, (model) => {
+ const [name, setName] = createSignal(model.name)
+ const [description, setDescription] = createSignal(model.description)
+
+ return {
+ id: model.id,
+ get name() {
+ return name()
+ },
+ get description() {
+ return description()
+ },
+ setName,
+ setDescription,
+ }
+})
+```
+
+## Arguments
+
+| Name | Type | Description |
+| :---- | :----------------------------- | :----------------------- |
+| list | `() => readonly T[]` | The source array to map. |
+| mapFn | `(v: T, i: () => number) => U` | The mapping function. |
+
+
+---
+title: mergeProps
+---
+
+```ts
+import { mergeProps } from "solid-js"
+
+function mergeProps(...sources: any): any
+
+```
+
+A reactive object **merge** method.
+Useful for setting default props for components in case caller doesn't provide them.
+Or cloning the props object including reactive properties.
+
+This method works by using a proxy and resolving properties in reverse order.
+This allows for dynamic tracking of properties that aren't present when the prop object is first merged.
+
+```ts
+// default props
+props = mergeProps({ name: "Smith" }, props)
+
+// clone props
+newProps = mergeProps(props)
+
+// merge props
+props = mergeProps(props, otherProps)
+```
+
+
+---
+title: observable
+---
+
+```ts
+import { observable } from "solid-js"
+
+function observable(input: () => T): Observable
+
+```
+
+This method takes a signal and produces an Observable.
+You can consume it from another Observable library of your choice, typically with the `from` operator.
+
+```ts
+// How to integrate rxjs with a Solid signal
+import { observable } from "solid-js"
+import { from } from "rxjs"
+
+const [s, set] = createSignal(0)
+
+const obsv$ = from(observable(s))
+
+obsv$.subscribe((v) => console.log(v))
+```
+
+You can also use `from` without rxjs; check out this [page](/reference/reactive-utilities/from).
+
+
+---
+title: on
+---
+
+```ts
+import { on } from "solid-js"
+
+function on any> | (() => any), U>(
+ deps: T,
+ fn: (input: T, prevInput: T, prevValue?: U) => U,
+ options: { defer?: boolean } = {}
+): (prevValue?: U) => U | undefined
+```
+
+`on` is designed to be passed into a computation to make its dependencies explicit.
+If an array of dependencies is passed, `input` and `prevInput` are arrays.
+
+```ts
+createEffect(on(a, (v) => console.log(v, b())));
+
+// is equivalent to:
+createEffect(() => {
+ const v = a();
+ untrack(() => console.log(v, b()));
+});
+```
+
+You can also not run the computation immediately and instead opt in for it to only run on change by setting the defer option to true.
+
+```ts
+// doesn't run immediately
+createEffect(on(a, (v) => console.log(v), { defer: true }));
+
+setA("new"); // now it runs
+```
+
+## Using `on` with stores
+
+
+ Please note that on stores and mutable, adding or removing a property from the
+ parent object will trigger an effect. See [`createMutable`](/reference/store-utilities/create-mutable)
+
+
+
+```ts
+const [state, setState] = createStore({ a: 1, b: 2 });
+
+// this will not work
+createEffect(on(state.a, (v) => console.log(v)));
+
+setState({ a: 3 }); // logs nothing
+
+// instead, use an arrow function
+createEffect(
+ on(
+ () => state.a,
+ (v) => console.log(v)
+ )
+);
+
+setState({ a: 4 }); // logs 4
+```
+
+## Arguments and options
+
+| Argument | Type | Description |
+| :------- | :--------------------------------------------- | :------------------------------------------------ |
+| deps | `T` | The dependencies to watch. |
+| fn | `(input: T, prevInput: T, prevValue?: U) => U` | The function to run when the dependencies change. |
+| options | `{ defer?: boolean }` | Options to configure the effect. |
+
+
+---
+title: runWithOwner
+order: 5
+---
+
+```ts
+import { runWithOwner } from "solid-js"
+import type { Owner } from "solid-js"
+
+function runWithOwner(owner: Owner, fn: (() => void) => T): T
+```
+
+Executes the given function under the provided owner, instead of (and without affecting) the owner of the outer scope.
+By default, computations created by `createEffect`, `createMemo`, etc. are owned by the owner of the currently executing code (the return value of `getOwner`), so in particular these will get disposed when their owner does.
+Calling `runWithOwner` provides a way to override this default to a manually specified owner (typically, the return value from a previous call to `getOwner`), enabling more precise control of when computations get disposed.
+
+Having a (correct) owner is important for two reasons:
+
+- Computations without an owner cannot be cleaned up.
+For example, if you call `createEffect` without an owner (e.g., in the global scope), the effect will continue running forever, instead of being disposed when its owner gets disposed.
+
+- `useContext` obtains context by walking up the owner tree to find the nearest ancestor providing the desired context.
+So without an owner you cannot look up any provided context (and with the wrong owner, you might obtain the wrong context).
+
+Manually setting the owner is especially helpful when doing reactivity outside of any owner scope.
+In particular, asynchronous computation (via either `async` functions or callbacks like `setTimeout`) lose their automatically set owner, so remembering the original owner via `getOwner` and restoring it via `runWithOwner` is necessary in these cases.
+For example:
+
+```ts
+const owner = getOwner()
+setTimeout(() => {
+ // This callback gets run without owner.
+ // Restore owner via runWithOwner:
+ runWithOwner(owner, () => {
+ const foo = useContext(FooContext)
+ createEffect(() => {
+ console.log(foo)
+ })
+ })
+}, 1000)
+```
+
+**Note:** that owners are not what determines dependency tracking, so `runWithOwner` does not help with tracking in asynchronous functions; use of reactive state in the asynchronous part (e.g. after the first `await`) will not be tracked as a dependency.
+
+
+---
+title: splitProps
+---
+
+```ts
+import { splitProps } from "solid-js"
+
+function splitProps(
+ props: T,
+ ...keys: Array<(keyof T)[]>
+): [...parts: Partial]
+
+```
+
+Splits a reactive object by keys.
+
+It takes a reactive object and any number of arrays of keys; for each array of keys, it will return a reactive object with just those properties of the original object.
+The last reactive object in the returned array will have any leftover properties of the original object.
+
+This can be useful if you want to consume a subset of props and pass the rest to a child.
+
+```tsx
+function MyComponent(props) {
+ const [local, others] = splitProps(props, ["children"])
+
+ return (
+ <>
+
{local.children}
+
+ >
+ )
+}
+```
+
+Because `splitProps` takes any number of arrays, we can split a props object as much as we wish (if, for example, we had multiple child components that each required a subset of the props).
+
+Let's say a component was passed six props:
+
+```tsx
+;
+// ...
+
+function MyComponent(props) {
+ console.log(props) // {a: 1, b: 2, c: 3, d: 4, e: 5, foo: "bar"}
+ const [vowels, consonants, leftovers] = splitProps(
+ props,
+ ["a", "e"],
+ ["b", "c", "d"]
+ )
+ console.log(vowels) // {a: 1, e: 5}
+ console.log(consonants) // {b: 2, c: 3, d: 4}
+ console.log(leftovers.foo) // bar
+}
+```
+
+
+---
+title: startTransition
+---
+
+```ts
+import { startTransition } from "solid-js"
+
+function startTransition: (fn: () => void) => Promise
+
+```
+
+Similar to `useTransition` except there is no associated pending state.
+This one can just be used directly to start the Transition.
+
+
+---
+title: untrack
+---
+
+Ignores tracking any of the dependencies in the executing code block and returns the value. This helper is useful when a certain `prop` will never update and thus it is ok to use it outside of the reactive context.
+
+```tsx title="component.tsx"
+import { untrack } from "solid-js"
+
+export function Component(props) {
+ const value = untrack(() => props.value)
+
+ return
{value}
+ }
+}
+```
+
+## Initial and Default Values
+
+It is not necessary to manually untrack values that are suppose to serve as a default or initial value to a signal. Even with the linter configured to enforce tracking, the linter will accept it when a `prop` is prefixed with `default` or `initial` as it is a common pattern to use them as such.
+
+
+
+
+
+---
+title: useTransition
+---
+
+```ts
+import { useTransition } from "solid-js"
+
+function useTransition(): [
+ pending: () => boolean,
+ startTransition: (fn: () => void) => Promise
+]
+
+```
+
+Used to batch async updates in a transaction deferring commit until all async processes are complete.
+This is tied into Suspense and only tracks resources read under Suspense boundaries.
+
+```ts
+const [isPending, start] = useTransition();
+
+// check if transitioning
+isPending();
+
+// wrap in transition
+start(() => setSignal(newValue), () => /* transition is done */)
+```
+
+
+---
+title: DEV
+---
+
+```ts
+import { DEV } from "solid-js"
+
+const DEV: object | undefined
+```
+
+On the client, Solid provides (via [conditional exports](https://nodejs.org/api/packages.html#conditional-exports)) different builds depending on whether the **development** condition is set.
+Development mode provides some additional checking — e.g. detecting accidental use of multiple instances of Solid — which are removed in production builds.
+
+If you want code to run only in development mode (most useful in libraries), you can check whether the **DEV** export is defined.
+Note that it is always defined on the server, so you may want to combine with [isServer](/reference/rendering/is-server):
+
+```ts
+import { DEV } from "solid-js"
+import { isServer } from "solid-js/web"
+
+if (DEV && !isServer) {
+ console.log(...);
+}
+```
+
+
+---
+title: hydrate
+---
+
+```ts
+import { hydrate } from "solid-js/web"
+import type { JSX } from "solid-js"
+import type { MountableElement } from "solid-js/web"
+
+function hydrate(
+ fn: () => JSX.Element,
+ node: MountableElement,
+ options?: { renderId?: string; owner?: unknown }
+): () => void
+
+```
+
+This method is similar to `render` except that it attempts to rehydrate what is already rendered to the DOM.
+When initializing in the browser a page has already been server rendered.
+
+```ts
+const dispose = hydrate(App, document.getElementById("app"))
+```
+
+## Parameters
+
+| Prop | type | description |
+| -------------------- | ------------------ | ----------------------------------------------- |
+| fn | `() => JSX.Element`| Function that returns the application code. |
+| node | MountableElement | DOM Element to mount the application to |
+| options.renderId | string | |
+| options.owner | unknown | |
+
+---
+title: hydrationScript
+---
+
+```ts
+import { generateHydrationScript, HydrationScript } from "solid-js/web"
+import type { JSX } from "solid-js"
+
+function generateHydrationScript(options: {
+ nonce?: string
+ eventNames?: string[]
+}): string
+
+function HydrationScript(props: {
+ nonce?: string
+ eventNames?: string[]
+}): JSX.Element
+
+```
+
+Hydration Script is a special script that should be placed once on the page to bootstrap hydration before Solid's runtime has loaded.
+It comes both as a function that can be called and inserted in an HTML string, or as a Component if you are rendering JSX from the `` tag.
+
+The options are for the **nonce** to be put on the script tag and any event names for that Solid should capture before scripts have loaded and replay during hydration.
+These events are limited to those that Solid delegates which include most UI Events that are composed and bubble.
+By default it is only click and input events.
+
+
+---
+title: isServer
+---
+
+```ts
+import { isServer } from "solid-js/web"
+
+const isServer: boolean
+
+```
+
+This indicates that the code is being run as the server or browser bundle.
+As the underlying runtimes export this as a constant boolean it allows bundlers to eliminate the code and their used imports from the respective bundles.
+
+```ts
+import { isServer } from "solid-js/web";
+
+if (isServer) {
+ // I will never make it to the browser bundle
+} else {
+ // won't be run on the server;
+}
+```
+
+
+---
+title: renderToStream
+---
+
+```ts
+import { renderToStream } from "solid-js/web"
+
+function renderToStream(
+ fn: () => T,
+ options?: {
+ nonce?: string
+ renderId?: string
+ onCompleteShell?: () => void
+ onCompleteAll?: () => void
+ }
+): {
+ pipe: (writable: { write: (v: string) => void }) => void
+ pipeTo: (writable: WritableStream) => void
+}
+
+```
+
+This method renders to a stream.
+It renders the content synchronously including any Suspense fallback placeholders, and then continues to stream the data and HTML from any async resource as it completes.
+
+```ts
+// node
+renderToStream(App).pipe(res)
+
+// web stream
+const { readable, writable } = new TransformStream()
+renderToStream(App).pipeTo(writable)
+```
+
+`onCompleteShell` fires when synchronous rendering is complete before writing the first flush to the stream out to the browser.
+`onCompleteAll` is called when all server Suspense boundaries have settled.
+`renderId` is used to namespace renders when having multiple top level roots.
+
+
+ This API replaces the previous pipeToWritable and pipeToNodeWritable
+ APIs.
+
+
+## Options
+
+| Name | Type | Description |
+| --------------- | ---------- | ---------------------------------------------------------------- |
+| nonce | string | The nonce to use for inline scripts. |
+| renderId | string | The id to use for this render. |
+| onCompleteShell | () => void | A callback that fires when the shell is complete. |
+| onCompleteAll | () => void | A callback that fires when all Suspense boundaries have settled. |
+
+
+---
+title: renderToStringAsync
+---
+
+```ts
+import { renderToStringAsync } from "solid-js/web"
+
+function renderToStringAsync(
+ fn: () => T,
+ options?: {
+ timeoutMs?: number
+ renderId?: string
+ nonce?: string
+ }
+): Promise
+
+```
+
+Same as `renderToString` except that it will wait for all `` boundaries to resolve before returning the results.
+Resource data is automatically serialized into the script tag and will be hydrated on client load.
+
+`renderId` is used to namespace renders when having multiple top level roots.
+
+```ts
+const html = await renderToStringAsync(App)
+```
+
+## Options
+
+| Name | Type | Description |
+| ----------- | -------- | -------------------------------------------------------------------------------------------- |
+| `timeoutMs` | `number` | The number of milliseconds to wait for a `` boundary to resolve before timing out. |
+| `renderId` | `string` | The id to use for the render. |
+| `nonce` | `string` | The nonce to use for the script tag. |
+
+
+---
+title: renderToString
+---
+
+```ts
+import { renderToString } from "solid-js/web"
+
+function renderToString(
+ fn: () => T,
+ options?: {
+ nonce?: string
+ renderId?: string
+ }
+): string
+
+```
+
+Renders to a string synchronously.
+The function also generates a script tag for progressive hydration.
+Options include eventNames to listen to before the page loads and play back on hydration, and nonce to put on the script tag.
+
+`renderId` is used to namespace renders when having multiple top level roots.
+
+```ts
+const html = renderToString(App)
+```
+
+## Options
+
+| Name | Type | Description |
+| ---------- | -------- | ------------------------------------ |
+| `nonce` | `string` | The nonce to use for the script tag. |
+| `renderId` | `string` | The id to use for the script tag. |
+
+
+---
+title: render
+---
+
+```ts
+import { render } from "solid-js/web"
+import type { JSX } from "solid-js"
+import type { MountableElement } from "solid-js/web"
+
+function render(
+ code: () => JSX.Element,
+ element: MountableElement
+): () => void
+
+```
+
+This is the browser app entry point.
+Provide a top-level component function and an element to mount to.
+It is recommended this element be empty: while `render` will just append children, the returned dispose function will remove all children.
+
+```ts
+const dispose = render(App, document.getElementById("app"))
+// or
+const dispose = render(() => , document.getElementById("app"))
+```
+
+It's important that the first argument is a function: do not pass JSX directly (as in `render(, ...)`), because this will call App before render can set up a root to track signal dependencies within App.
+
+## Parameters
+
+| Argument | Type | Description |
+| -------------------- | ------------------- | ----------------------------------------------- |
+| code | `() => JSX.Element` | Function that returns the application code. |
+| element | MountableElement | DOM Element to mount the application to |
+
+---
+title: createComputed
+---
+
+```ts
+import { createComputed } from "solid-js"
+
+function createComputed(fn: (v: T) => T, value?: T): void
+
+```
+
+`createComputed` creates a new computation that immediately runs the given function in a tracking scope, thus automatically tracking its dependencies, and automatically reruns the function whenever the dependencies changes.
+The function gets called with an argument equal to the value returned from the function's last execution, or on the first call, equal to the optional second argument to `createComputed`.
+Note that the return value of the function is not otherwise exposed; in particular, createComputed has no return value.
+
+`createComputed` is the most immediate form of reactivity in Solid, and is most useful for building other reactive primitives.
+For example, some other Solid primitives are built from `createComputed`.
+However, it should be used with care, as `createComputed` can easily cause more unnecessary updates than other reactive primitives.
+Before using it, consider the closely related primitives [`createMemo`](/reference/basic-reactivity/create-memo) and [`createRenderEffect`](/reference/secondary-primitives/create-render-effect).
+
+Like `createMemo`, `createComputed` calls its function immediately on updates (unless you're in a [batch](/reference/reactive-utilities/batch), [effect](/reference/basic-reactivity/create-effect), or [transition](/reference/reactive-utilities/use-transition)).
+However, while `createMemo` functions should be pure (not set any signals), `createComputed` functions can set signals.
+Related, `createMemo` offers a readonly signal for the return value of the function, whereas to do the same with `createComputed` you would need to set a signal within the function.
+If it is possible to use pure functions and `createMemo`, this is likely more efficient, as Solid optimizes the execution order of memo updates, whereas updating a signal within `createComputed` will immediately trigger reactive updates some of which may turn out to be unnecessary.
+
+## Arguments
+
+| Name | Type | Description |
+| :------ | :------------ | :----------------------------------------- |
+| `fn` | `(v: T) => T` | The function to run in a tracking scope. |
+| `value` | `T` | The initial value to pass to the function. |
+
+
+---
+title: createDeferred
+---
+
+```ts
+import { createDeferred } from "solid-js"
+
+function createDeferred(
+ source: () => T,
+ options?: {
+ timeoutMs?: number
+ equals?: false | ((prev: T, next: T) => boolean)
+ name?: string
+ }
+): () => T
+
+```
+
+Creates a readonly that only notifies downstream changes when the browser is idle.
+`timeoutMs` is the maximum time to wait before forcing the update.
+
+## Options
+
+| Name | Type | Description |
+| --------- | ------------------------------------------ | ------------------------------------------------------ |
+| timeoutMs | `number` | The maximum time to wait before forcing the update. |
+| equals | `false or ((prev: T, next: T) => boolean)` | A function that returns true if the value has changed. |
+| name | `string` | The name of the readonly. |
+
+
+
+---
+title: createReaction
+---
+
+```ts
+import { createReaction } from "solid-js"
+
+function createReaction(onInvalidate: () => void): (fn: () => void) => void
+
+```
+
+Sometimes it is useful to separate tracking from re-execution.
+This primitive registers a side effect that is run the first time the expression wrapped by the returned tracking function is notified of a change.
+
+```ts
+const [s, set] = createSignal("start")
+
+const track = createReaction(() => console.log("something"))
+
+// run the reaction next time `s` changes.
+track(() => s())
+
+set("end") // "something"
+
+set("final") // no-op since the reaction only runs on the first update, need to call `track` again.
+```
+
+
+---
+title: createRenderEffect
+---
+
+```ts
+import { createRenderEffect } from "solid-js"
+
+function createRenderEffect(fn: (v: T) => T, value?: T): void
+
+```
+
+A render effect is a computation similar to a regular effect (as created by [`createEffect`](/reference/basic-reactivity/create-effect)), but differs in when Solid schedules the first execution of the effect function.
+While `createEffect` waits for the current rendering phase to be complete, `createRenderEffect` immediately calls the function.
+Thus the effect runs as DOM elements are being created and updated, but possibly before specific elements of interest have been created, and probably before those elements have been connected to the document.
+In particular, **refs** will not be set before the initial effect call.
+Indeed, Solid uses `createRenderEffect` to implement the rendering phase itself, including setting of **refs**.
+
+Reactive updates to render effects are identical to effects: they queue up in response to a reactive change (e.g., a single signal update, or a batch of changes, or collective changes during an entire render phase) and run in a single [`batch`](/reference/reactive-utilities/batch) afterward (together with effects).
+In particular, all signal updates within a render effect are batched.
+
+Here is an example of the behavior. (Compare with the example in [`createEffect`](/reference/basic-reactivity/create-effect).)
+
+```ts
+// assume this code is in a component function, so is part of a rendering phase
+const [count, setCount] = createSignal(0)
+
+// this effect prints count at the beginning and when it changes
+createRenderEffect(() => console.log("count =", count()))
+// render effect runs immediately, printing `count = 0`
+console.log("hello")
+setCount(1) // effect won't run yet
+setCount(2) // effect won't run yet
+
+queueMicrotask(() => {
+ // now `count = 2` will print
+ console.log("microtask")
+ setCount(3) // immediately prints `count = 3`
+ console.log("goodbye")
+})
+
+// --- overall output: ---
+// count = 0 [this is the only added line compared to createEffect]
+// hello
+// count = 2
+// microtask
+// count = 3
+// goodbye
+```
+
+Just like `createEffect`, the effect function gets called with an argument equal to the value returned from the effect function's last execution, or on the first call, equal to the optional second argument of `createRenderEffect`.
+
+## Arguments
+
+| Name | Type | Description |
+| :------ | :------------ | :----------------------------------------------------- |
+| `fn` | `(v: T) => T` | The effect function to be called. |
+| `value` | `T` | The initial value to be passed to the effect function. |
+
+
+---
+title: createSelector
+---
+
+```ts
+import { createSelector } from "solid-js"
+
+function createSelector(
+ source: () => T,
+ fn?: (a: U, b: T) => boolean
+): (key: U) => boolean
+```
+
+Creates a parameterized derived boolean signal `selector(key)` that indicates
+whether `key` is equal to the current value of the `source` signal.
+These signals are optimized to notify each subscriber only when their `key`
+starts or stops matching the reactive `source` value
+(instead of every time `key` changes).
+If you have *n* different subscribers with different keys,
+and the `source` value changes from `a` to `b`, then
+instead of all *n* subscribers updating,
+at most two subscribers will update:
+the signal with key `a` will change to `false`,
+and the signal with key `b` will change to `true`.
+Thus it reduces from *n* updates to 2 updates.
+
+Useful for defining the selection state of several selectable elements.
+For example:
+
+```tsx
+const [selectedId, setSelectedId] = createSignal()
+const isSelected = createSelector(selectedId)
+
+
+ {(item) =>
{item.name}
}
+
+```
+
+In the code above, each `li` element receives an `active` class
+exactly when the corresponding `item.id` is equal to `selectedId()`.
+When the `selectedId` signal changes, the `li` element(s) that previously
+had previously matching `id` get the `active` class removed, and the
+`li` element(s) that now have a matching `id` get the `active` class added.
+All other `li` elements get skipped, so if `id`s are distinct,
+only 2 DOM operations get performed.
+
+By contrast, the following code would perform `list().length` DOM operations
+every time the `selectedId` signal changes:
+
+```tsx
+const [selectedId, setSelectedId] = createSignal()
+
+
+ {(item) =>
{item.name}
}
+
+```
+
+## Arguments
+
+| Name | Type | Description |
+| :------- | :------------------------ | :------------------------------------------- |
+| `source` | `() => T` | The source signal to get the value from and compare with keys. |
+| `fn` | `(a: U, b: T) => boolean` | A function to compare the key and the value, returning whether they should be treated as equal. Default: `===` |
+
+
+---
+title: getRequestEvent
+---
+
+Solid uses Async Local Storage as a way of injecting the request context anywhere on the server.
+The server provides a utility function to access this context
+(called a `RequestEvent`).
+
+```js
+import { getRequestEvent } from "solid-js/web"
+import type { RequestEvent } from "solid-js/web"
+
+function getRequestEvent(): RequestEvent | undefined
+```
+
+You can retrieve the request event by calling `getRequestEvent`:
+
+```js
+import { getRequestEvent } from "solid-js/web"
+
+const event = getRequestEvent()
+```
+
+## Request
+
+`.request` is the most important property of the `RequestEvent`.
+This is a Web [Request object](https://developer.mozilla.org/en-US/docs/Web/API/Request) that represents the current request to the server.
+You can access properties off of it such as `url` and `headers`.
+ `body`, however, does not typically need to be handled directly for things such as server functions or rendering, which already handle mapping.
+
+```js
+import { getRequestEvent } from "solid-js/web"
+
+const event = getRequestEvent();
+if (event) {
+ const auth = event.request.headers.get("Authorization");
+}
+```
+
+## Response
+
+The `getRequestEvent` can also be used to stub out the Response - this extends the [options that can be passed to the `Response constructor`](https://developer.mozilla.org/en-US/docs/Web/API/Response/Response#options).
+This is kept up to date so it can be used to read and write headers and status for the current response.
+
+```js
+import { getRequestEvent } from "solid-js/web"
+
+const event = getRequestEvent();
+if (event) {
+ event.response.headers.append("Set-Cookie", "foo=hello");
+ event.response.status = 201;
+}
+```
+
+### Change event.response or create a new Response
+
+The `getRequestEvent` event is considered global and lasts the life of the request.
+Therefore, if you are calling a server function on the server during SSR or an RPC call, setting values on `event.response` will reflect on that request.
+
+The returned response will only impact the response when it is an RPC call.
+This is important because some headers previously set may not be needed to be set for the whole page, but only for a specific request.
+
+**Note:** This is important to keep in mind when choosing where to set headers and responses.
+
+
+ See this guide on [Request
+ Events](/solid-start/advanced/request-events).
+
+
+
+---
+title: createMutable
+---
+
+`createMutable` creates a new mutable Store proxy object that provides a way to selectively trigger updates only when values change.
+
+By intercepting property access, it allows automatic tracking of deep nesting via proxy making it useful for integrating external systems or serving as a compatibility layer with frameworks like MobX or Vue.
+
+```tsx
+import { createMutable } from "solid-js/store"
+import type { Store, StoreNode } from "solid-js/store"
+
+function createMutable(state: T | Store): Store;
+```
+
+
+ It's important to recognize that a mutable state, which can be passed around and modified anywhere, may complicate the code structure and increase the risk of breaking unidirectional flow.
+
+ For a more robust alternative, it is generally recommended to use `createStore` instead.
+ Additionally, the [`produce`](/reference/store-utilities/produce) utility can provide many of these same benefits without the associated downsides.
+
+
+```tsx
+import { createMutable } from "solid-js/store"
+
+const state = createMutable({
+ someValue: 0,
+ list: [],
+});
+
+// read value
+state.someValue;
+
+// set value
+state.someValue = 5;
+
+state.list.push(anotherValue);
+```
+
+Mutables support setters along with getters.
+
+```tsx
+const user = createMutable({
+ firstName: "John",
+ lastName: "Smith",
+ get fullName() {
+ return `${this.firstName} ${this.lastName}`;
+ },
+ set setFullName(value) {
+ [this.firstName, this.lastName] = value.split(" ");
+ },
+});
+```
+
+
+
+---
+title: createStore
+---
+
+Stores were intentionally designed to manage data structures like objects and arrays but are capable of handling other data types, such as strings and numbers.
+
+## Types Signature
+
+```tsx
+import { createStore } from "solid-js/store"
+import type { StoreNode, Store, SetStoreFunction } from "solid-js/store"
+
+function createStore(
+ state: T | Store
+): [get: Store, set: SetStoreFunction];
+
+type Store = T; // conceptually readonly, but not typed as such
+```
+
+## Usage
+
+```tsx
+import { createStore } from "solid-js/store";
+
+// Initialize store
+const [store, setStore] = createStore({
+ userCount: 3,
+ users: [
+ {
+ id: 0,
+ username: "felix909",
+ location: "England",
+ loggedIn: false,
+ },
+ {
+ id: 1,
+ username: "tracy634",
+ location: "Canada",
+ loggedIn: true,
+ },
+ {
+ id: 1,
+ username: "johny123",
+ location: "India",
+ loggedIn: true,
+ },
+ ],
+});
+```
+
+## Getter
+
+Store objects support the use of getters to store derived values.
+
+```tsx
+const [state, setState] = createStore({
+ user: {
+ firstName: "John",
+ lastName: "Smith",
+ get fullName() {
+ return `${this.firstName} ${this.lastName}`;
+ },
+ },
+});
+```
+
+## Setter
+
+Changes can take the form of function that passes previous state and returns new state or a value.
+Objects are always shallowly merged. Set values to undefined to delete them from the Store.
+In TypeScript, you can delete a value by using a non-null assertion, like `undefined!`.
+
+```tsx
+const [state, setState] = createStore({
+ firstName: "John",
+ lastName: "Miller",
+});
+
+setState({ firstName: "Johnny", middleName: "Lee" });
+// ({ firstName: 'Johnny', middleName: 'Lee', lastName: 'Miller' })
+
+setState((state) => ({ preferredName: state.firstName, lastName: "Milner" }));
+// ({ firstName: 'Johnny', preferredName: 'Johnny', middleName: 'Lee', lastName: 'Milner' })
+```
+
+---
+
+To learn more about using stores check the [Stores Guide](/concepts/stores), and the **Store utilities** section for more advanced APIs.
+
+
+---
+title: modifyMutable
+---
+
+`modifyMutable` streamlines the process of making multiple changes to a mutable Store, as obtained through the use of [`createMutable`](/reference/store-utilities/create-mutable).
+
+It operates within a single [`batch`](/reference/reactive-utilities/batch), ensuring that dependent computations are updated just once, rather than triggering updates for each individual change.
+
+```tsx
+import { modifyMutable } from "solid-js/store"
+
+function modifyMutable(mutable: T, modifier: (state: T) => T): void
+```
+
+The function takes two arguments:
+
+1. The first argument is the mutable Store that needs modification.
+2. The second argument is a Store modifier, which could be one of those returned by [`reconcile`](/reference/store-utilities/reconcile).
+
+
+ When passing in your own modifier function, it's important to be aware that
+ its argument is an unwrapped version of the store.
+
+
+For example, if the UI depends on multiple fields of a mutable:
+
+```tsx
+import { createMutable } from "solid-js/store"
+
+const state = createMutable({
+ user: {
+ firstName: "John",
+ lastName: "Smith",
+ },
+});
+
+
;
+```
+
+Modifying n fields in sequence will cause the UI to update n times:
+
+```tsx
+state.user.firstName = "Jane";
+state.user.lastName = "Doe";
+```
+
+To trigger just a single update, the fields can be modified using a `batch`:
+
+```tsx
+import { batch } from "solid-js"
+
+batch(() => {
+ state.user.firstName = "Jane";
+ state.user.lastName = "Doe";
+});
+```
+
+`modifyMutable` combined with [`reconcile`](/reference/store-utilities/reconcile) or [`produce`](/reference/store-utilities/produce) provides two alternate ways to do similar things:
+
+```tsx
+import { modifyMutable, reconcile } from "solid-js/store"
+
+// Replace state.user with the specified object (deleting any other fields)
+modifyMutable(
+ state.user,
+ reconcile({
+ firstName: "Jane",
+ lastName: "Doe",
+ })
+);
+```
+
+```tsx
+import { modifyMutable, produce } from "solid-js/store"
+
+// Modify two fields in a batch, triggering just one update
+modifyMutable(
+ state,
+ produce((state) => {
+ state.user.firstName = "Jane";
+ state.user.lastName = "Doe";
+ })
+);
+```
+
+
+---
+title: produce
+---
+
+`produce` is an [Immer](https://immerjs.github.io/immer/) inspired API for Solid's Store objects that allows for localized mutation.
+
+```ts
+import { produce } from "solid-js/store"
+import type { NotWrappable, Store } from "solid-js/store"
+
+function produce(
+ fn: (state: T) => void
+): (
+ state: T extends NotWrappable ? T : Store
+) => T extends NotWrappable ? T : Store;
+```
+
+For use with `createStore`:
+
+```tsx
+import { produce } from "solid-js/store";
+
+const [state, setState] = createStore({
+ user: {
+ name: "John",
+ age: 30,
+ },
+ list: ["book", "pen"],
+});
+
+setState(
+ produce((state) => {
+ state.user.name = "Jane";
+ state.list.push("pencil");
+ })
+);
+```
+
+
+---
+title: reconcile
+---
+
+`reconcile` is designed for diffing data changes in situations where granular updates cannot be applied.
+This is useful when dealing with immutable data from stores or handling large API responses.
+
+```tsx
+import { reconcile } from "solid-js/store"
+import type { NotWrappable, Store } from "solid-js/store"
+
+function reconcile(
+ value: T | Store,
+ options?: {
+ key?: string | null;
+ merge?: boolean;
+ } = { key: "id" }
+): (
+ state: T extends NotWrappable ? T : Store
+) => T extends NotWrappable ? T : Store
+```
+
+`reconcile` has a `key` option that can be used when available to match items.
+The `value` accepts either a value of type `T` or a Store containing values of type `T`.
+This represents the data to be reconciled.
+
+The `reconcile` function helps manage data changes by performing a diffing process, making it particularly handy in scenarios where applying granular updates is challenging or inefficient.
+
+The `key` and `merge` options provide flexibility to customize the reconciliation process based on specific needs.
+
+```ts
+// subscribing to an observable
+const unsubscribe = store.subscribe(({ todos }) => (
+ setState('todos', reconcile(todos));
+);
+onCleanup(() => unsubscribe());
+
+```
+
+##### Options
+
+| Option | Type | Default | Description |
+| ------ | ------- | ------- | ---------------------------------- |
+| key | string | "id" | Specifies the key to be used for matching items during reconciliation |
+| merge | boolean | false | When merge is false, referential checks are performed where possible to determine equality, and items that are not referentially equal are replaced. When merge is true, all diffing is pushed to the leaves, effectively morphing the previous data to the new value. |
+
+
+---
+title: unwrap
+---
+
+`unwrap` returns the underlying data in the store without a proxy.
+
+```tsx
+import { unwrap } from "solid-js/store"
+import type { Store } from "solid-js/store"
+
+function unwrap(store: Store): T
+```
+
+
+---
+title: "Auth"
+---
+
+Server functions can be used to protect sensitive resources like user data.
+
+```tsx
+"use server"
+
+async function getPrivatePosts() {
+ const user = await getUser()
+ if(!user) {
+ return null // or throw an error
+ }
+
+ return db.getPosts({ userId: user.id, private: true })
+}
+```
+
+The `getUser` function can be [implemented using sessions](/solid-start/advanced/session).
+
+## Protected Routes
+
+Routes can be protected by checking the user or session object during data fetching.
+This example uses [Solid Router](/solid-router).
+
+```tsx
+const getPrivatePosts = query(async function() {
+ "use server"
+ const user = await getUser()
+ if(!user) {
+ throw redirect("/login");
+ }
+
+ return db.getPosts({ userId: user.id, private: true })
+})
+
+export default function Page() {
+ const posts = createAsync(() => getPrivatePosts());
+}
+```
+
+Once the user hits this route, the router will attempt to fetch `getPrivatePosts` data.
+If the user is not signed in, `getPrivatePosts` will throw and the router will redirect to the login page.
+
+
+---
+title: "Middleware"
+---
+
+Middlewares may be included by passing file you specify in your start config.
+
+```js
+import { defineConfig } from "@solidjs/start/config";
+
+export default defineConfig({
+ middleware: "./src/middleware.ts"
+});
+```
+
+Inside the middleware file, you can export a `createMiddleware` function.
+
+```tsx
+import { createMiddleware } from "@solidjs/start/middleware";
+
+export default createMiddleware({
+ onRequest: [
+ event => {
+ console.log("GLOBAL", event.request.url);
+ }
+ ]
+});
+```
+
+Middleware supports 2 lifecycles: `onRequest` and `onBeforeResponse`. If you return a value from middleware it will respond with that, otherwise it will run the next one in the chain.
+
+---
+title: Request events
+---
+
+Request events in SolidStart are retrieved using the [`getRequestEvent`](/reference/server-utilities/get-request-event) from `@solidjs/web`.
+These requests happen anywhere on the server.
+
+## Locals
+
+SolidStart uses `event.locals` to pass around a local context where needed.
+
+When adding fields to `event.locals`, the fields can be typed:
+
+```tsx
+declare module "@solidjs/start/server" {
+ interface RequestEventLocals {
+ myNumber: number;
+ someString: string;
+ }
+}
+```
+
+## nativeEvent
+
+Sometimes access is still needed to the underlying event from [Vinxi](https://vinxi.vercel.app/).
+This can be accessed that using the `.nativeEvent` property, which is the underlying H3Event used, and can be passed to the helpers available in the ecosystem.
+Note that Vinxi HTTP helpers _do not_ treeshake so you can only import them in files that do not contain client or isomorphic code.
+
+Many of these events support Async Local Storage so this may not be needed.
+
+
+---
+title: Returning responses
+---
+
+In SolidStart, it is possible to return a Response object from a server function.
+[`solid-router`](/solid-router) knows how to handle certain responses with its [`cache`](/solid-router/reference/data-apis/cache) and [`action`](/solid-router/reference/data-apis/action) APIs.
+For Typescript, when returning a response using `solid-routers`'s `redirect`, `reload`, or `json` helpers, they will not impact the return value of the server function.
+
+While we suggest depending on the type of the function to handle errors differently, you can always return or throw a response.
+
+## Examples
+
+In the following example, the `hello` function will return a value of type `Promise<{ hello: string }>`:
+
+```tsx
+import { json } from "@solidjs/router";
+import { GET } from "@solidjs/start";
+
+const hello = GET(async (name: string) => {
+ "use server";
+ return json(
+ { hello: new Promise((r) => setTimeout(() => r(name), 1000)) },
+ { headers: { "cache-control": "max-age=60" } }
+ );
+});
+```
+
+However, in this example, since `redirect` and `reload` return `never` as their type, `getUser` can only return a value of type `Promise`:
+
+```tsx { 4, 10, 14}
+export async function getUser() {
+ "use server";
+
+ const session = await getSession();
+ const userId = session.data.userId;
+ if (userId === undefined) return redirect("/login");
+
+ try {
+ const user: User = await db.user.findUnique({ where: { id: userId } });
+ // throwing can awkward.
+ if (!user) return redirect("/login");
+ return user;
+ } catch {
+ // do stuff
+ throw redirect("/login");
+ }
+}
+```
+
+
+---
+title: "Sessions"
+---
+
+When user information is required, it is usually done by checking the request for information.
+The best way for the client and server to do that is using cookies.
+
+The `Request` object can be used to access the `Cookie` Headers, which can then be parsed to get the value for that specific cookie.
+For example, `"session"` can be used to identify the session.
+Fortunately, Nitro comes ready with helpers that enable this.
+
+For example, if you wanted to use a cookie to identify a user, you can use the `useSession` helper from `vinxi/http`:
+
+```tsx title="/lib/session.ts"
+import { useSession } from "vinxi/http";
+export async function getUser(request: Request) {
+ const session = await useSession({
+ password: process.env.SESSION_SECRET
+ });
+}
+```
+
+The session cookie can be used to get the session data about the request.
+How the session data is stored and retrieved, however, is up to the implementation of the `useSession`.
+
+Typically, `userId` will be saved in the session data and if it is not found, it indicates that the request was not authenticated.
+The `getUser` function returns a `null` when it does not find a user and if a user is found, it will be used to get the user from the database:
+
+```tsx title="/lib/session.ts"
+import { useSession } from "vinxi/http";
+
+export async function getUser(): Promise {
+ const session = await useSession({
+ password: process.env.SESSION_SECRET
+ });
+ const userId = session.data.userId;
+ if (!userId) return null;
+ return await store.getUser(userId);
+}
+```
+
+This helper can be used wherever you want to authenticate the request, including in server functions and [API routes](/solid-start/building-your-application/api-routes).
+
+Additionally, you can use it with [`cache`](/solid-router/reference/data-apis/cache) from `solid-router` to make sure that only authenticated users can access the data.
+That way if the user is not authenticated, the request will be redirected to the login page.
+
+```tsx title="/routes/api/store/admin.ts"
+import { query, createAsync, redirect } from "@solidjs/router";
+
+const getUsers = query(async (id: string) => {
+ "use server";
+ const user = await getUser();
+ if (!user) throw redirect("/login");
+ return store.getUsers(id, "*");
+}, "users");
+
+// page component
+export default function Users() {
+ const users = createAsync(() => getUsers());
+}
+```
+
+This also allows logging in and out of the session in a similar manner:
+
+```tsx title="/routes/session.server.ts"
+import { redirect } from "@solidjs/router";
+import { useSession } from "vinxi/http";
+
+type UserSession = {
+ userId?: number;
+};
+
+function getSession() {
+ return useSession({
+ password: process.env.SESSION_SECRET
+ });
+}
+
+export async function login(formData: FormData) {
+ const username = String(formData.get("username"));
+ const password = String(formData.get("password"));
+ // do validation
+ try {
+ const session = await getSession();
+ const user = await db.user.findUnique({ where: { username } });
+ if (!user || password !== user.password) return new Error("Invalid login");
+ await session.update((d: UserSession) => (d.userId = user!.id));
+ } catch (err) {
+ return err as Error;
+ }
+ throw redirect("/");
+}
+
+export async function logout() {
+ const session = await getSession();
+ await session.update((d: UserSession) => (d.userId = undefined));
+ throw redirect("/login");
+}
+```
+
+---
+title: WebSocket endpoint
+---
+
+WebSocket endpoint may be included by passing the ws handler file you specify in your start config.
+Note that this feature is [experimental on the Nitro server](https://nitro.unjs.io/guide/websocket#opt-in-to-the-experimental-feature) and its config may change in future releases of SolidStart. Use it with caution.
+
+```ts title="./app.config.ts"
+import { defineConfig } from "@solidjs/start/config";
+
+export default defineConfig({
+ server: {
+ experimental: {
+ websocket: true,
+ },
+ },
+}).addRouter({
+ name: "ws",
+ type: "http",
+ handler: "./src/ws.ts",
+ target: "server",
+ base: "/ws",
+});
+```
+
+Inside the ws file, you can export an eventHandler function to manage WebSocket connections and events:
+
+```tsx title="./src/ws.ts"
+import { eventHandler } from "vinxi/http";
+
+export default eventHandler({
+ handler() {},
+ websocket: {
+ async open(peer) {
+ console.log("open", peer.id, peer.url);
+ },
+ async message(peer, msg) {
+ const message = msg.text();
+ console.log("msg", peer.id, peer.url, message);
+ },
+ async close(peer, details) {
+ console.log("close", peer.id, peer.url);
+ },
+ async error(peer, error) {
+ console.log("error", peer.id, peer.url, error);
+ },
+ },
+});
+```
+
+
+---
+title: "API routes"
+---
+
+While Server Functions can be a good way to write server-side code for data needed by your UI, sometimes you need to expose API routes.
+Some reasons for wanting API Routes include:
+- There are additional clients that want to share this logic.
+- Exposing a GraphQL or tRPC endpoint.
+- Exposing a public facing REST API.
+- Writing webhooks or auth callback handlers for OAuth.
+- Having URLs not serving HTML, but other kinds of documents like PDFs or images.
+
+For these use cases, SolidStart provides a way to write these routes in a way that is easy to understand and maintain.
+API routes are just similar to other routes and follow the same filename conventions as [UI Routes](/solid-start/building-your-application/routing).
+
+The difference between API routes and UI routes is in what you should export from the file.
+UI routes export a default Solid component, while API Routes do not.
+Rather, they export functions that are named after the HTTP method that they handle.
+
+
+API routes are prioritized over page route alternatives.
+If you want to have them overlap at the same path remember to use `Accept` headers.
+Returning without a response in a `GET` route will fallback to page route handling.
+
+
+## Writing an API route
+
+To write an API route, you can create a file in a directory.
+While you can name this directory anything, it is common to name it `api` to indicate that the routes in this directory are for handling API requests:
+
+```tsx title="routes/api/test.ts"
+export function GET() {
+ // ...
+}
+
+export function POST() {
+ // ...
+}
+
+export function PATCH() {
+ // ...
+}
+
+export function DELETE() {
+ // ...
+}
+```
+
+API routes get passed an `APIEvent` object as their first argument.
+This object contains:
+- `request`: [`Request`](https://developer.mozilla.org/en-US/docs/Web/API/Request) object representing the request sent by the client.
+- `params`: Object that contains the dynamic route parameters. For example, if the route is `/api/users/:id`, and the request is made to `/api/users/123`, then `params` will be `{ id: 123 }`.
+- `fetch`: An internal `fetch` function that can be used to make requests to other API routes without worrying about the `origin` of the URL.
+
+An API route is expected to return JSON or a `Response` object.
+In order to handle all methods, you can define a handler function that binds multiple methods to it:
+
+```tsx title="routes/api/all.ts"
+async function handler() {
+ // ...
+}
+
+export const GET = handler;
+export const POST = handler;
+// ...
+```
+
+An example of an API route that returns products from a certain category and brand is shown below:
+
+```tsx title="routes/api/product/[category]/[brand].ts"
+import type { APIEvent } from "@solidjs/start/server";
+import store from "./store";
+
+export async function GET({ params }: APIEvent) {
+ console.log(`Category: ${params.category}, Brand: ${params.brand}`);
+ const products = await store.getProducts(params.category, params.brand);
+ return products;
+}
+```
+
+## Session management
+
+Since HTTP is a stateless protocol, you need to manage the state of the session on the server.
+For example, if you want to know who the user is, the most secure way of doing this is through the use of HTTP-only cookies.
+Cookies are a way to store data in the user's browser that persist in the browser between requests.
+
+The user's request is exposed through the `Request` object.
+Through parsing the [`Cookie`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cookie) header, the cookies can be accessed and any helpers from `vinxi/http` can be used to make that a bit easier.
+
+```tsx
+import type { APIEvent } from "@solidjs/start/server";
+import { getCookie } from "vinxi/http";
+import store from "./store";
+
+export async function GET(event: APIEvent) {
+ const userId = getCookie("userId");
+ if (!userId) {
+ return new Response("Not logged in", { status: 401 });
+ }
+ const user = await store.getUser(event.params.userId);
+ if (user.id !== userId) {
+ return new Response("Not authorized", { status: 403 });
+ }
+ return user;
+}
+```
+
+In this example, you can see that the `userId` is read from the cookie and then used to look up the user in the store.
+For more information on how to use cookies for secure session management, read the [session documentation](/solid-start/advanced/session).
+
+## Exposing a GraphQL API
+
+SolidStart makes it easy to [implement a GraphQL API](https://graphql.org/).
+GraphQL is a query language for APIs and a runtime for executing those queries by using a type system you define for your data.
+
+To implement a GraphQL API, you need to define a schema and resolvers.
+The `graphql` function takes a GraphQL schema and returns a function that can be used as an API route handler.
+
+First, to implement a GraphQL API, install the `graphql` library.
+Following that, you can implement your schema and resolvers in a file and then export a handler function that will be used as the API route:
+
+```tsx title="routes/graphql.ts"
+import { buildSchema, graphql } from "graphql";
+import type { APIEvent } from "@solidjs/start/server";
+
+// Define GraphQL Schema
+const schema = buildSchema(`
+ type Message {
+ message: String
+ }
+
+ type Query {
+ hello(input: String): Message
+ goodbye: String
+ }
+`);
+
+// Define GraphQL Resolvers
+const rootValue = {
+ hello: () => {
+ return {
+ message: "Hello World"
+ };
+ },
+ goodbye: () => {
+ return "Goodbye";
+ }
+};
+
+// request handler
+const handler = async (event: APIEvent) => {
+ // get request body
+ const body = await new Response(event.request.body).json();
+
+ // pass query and save results
+ const result = await graphql({ rootValue, schema, source: body.query });
+
+ // send query result
+ return result;
+};
+
+export const GET = handler;
+
+export const POST = handler;
+```
+
+## Exposing a tRPC server route
+
+[tRPC](https://trpc.io/) is a modern TypeScript-first API framework that is designed to be easy to use and understand.
+
+To expose a tRPC server route, you need to write your router.
+Once you have written your router, you can put it in a separate file so that you can export the type for your client.
+
+```tsx title="lib/router.ts"
+import { initTRPC } from "@trpc/server";
+import { wrap } from "@decs/typeschema";
+import { string } from "valibot";
+
+const t = initTRPC.create();
+
+export const appRouter = t.router({
+ hello: t.procedure.input(wrap(string())).query(({ input }) => {
+ return `hello ${input ?? "world"}`;
+ })
+});
+
+export type AppRouter = typeof appRouter;
+```
+
+An example of a simple client that you can use to fetch data from your tRPC server is shown below:
+
+```tsx title="lib/trpc.ts"
+import { createTRPCProxyClient, httpBatchLink, loggerLink } from "@trpc/client";
+import type { AppRouter } from "./router";
+
+export const client = createTRPCProxyClient({
+ links: [loggerLink(), httpBatchLink({ url: "http://localhost:3000/api/trpc" })]
+});
+```
+
+Finally, you can use the `fetch` adapter to write an API route that acts as the tRPC server.
+
+```tsx title="routes/api/trpc/[trpc].ts"
+import { type APIEvent } from "@solidjs/start/server";
+import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
+import { appRouter } from "~/lib/router";
+
+const handler = (event: APIEvent) =>
+ fetchRequestHandler({
+ endpoint: "/api/trpc",
+ req: event.request,
+ router: appRouter,
+ createContext: () => ({})
+ });
+
+export const GET = handler;
+
+export const POST = handler;
+```
+
+To learn more about tRPC, you can read the [tRPC documentation](https://trpc.io/docs).
+
+
+---
+title: "CSS and styling"
+---
+
+SolidStart is a standards-based framework that, instead of modifying the behavior of the [`