API โ€บ @qwik.dev/qwik

"q:slot"

'q:slot'?: string;

$

Qwik Optimizer marker function.

Use $(...) to tell Qwik Optimizer to extract the expression in $(...) into a lazy-loadable resource referenced by QRL.

$: <T>(expression: T) => QRL<T>;

Parameter

Type

Description

expression

T

Expression which should be lazy loaded

QRL<T>

Edit this section

cache

cache(policyOrMilliseconds: number | 'immutable'): void;

Parameter

Type

Description

policyOrMilliseconds

number | 'immutable'

void

ClassList

A class list can be a string, a boolean, an array, or an object.

If it's an array, each item is a class list and they are all added.

If it's an object, then the keys are class name strings, and the values are booleans that determine if the class name string should be added or not.

export type ClassList =
  | string
  | undefined
  | null
  | false
  | Record<string, boolean | string | number | null | undefined>
  | ClassList[];

References: ClassList

Edit this section

cleanup

cleanup(): void;

Returns:

void

Component

Type representing the Qwik component.

Component is the type returned by invoking component$.

interface MyComponentProps {
  someProp: string;
}
const MyComponent: Component<MyComponentProps> = component$(
  (props: MyComponentProps) => {
    return <span>{props.someProp}</span>;
  },
);
export type Component<PROPS = unknown> = FunctionComponent<PublicProps<PROPS>>;

References: FunctionComponent, PublicProps

Edit this section

component$

Declare a Qwik component that can be used to create UI.

Use component$ to declare a Qwik component. A Qwik component is a special kind of component that allows the Qwik framework to lazy load and execute the component independently of other Qwik components as well as lazy load the component's life-cycle hooks and event handlers.

Side note: You can also declare regular (standard JSX) components that will have standard synchronous behavior.

Qwik component is a facade that describes how the component should be used without forcing the implementation of the component to be eagerly loaded. A minimum Qwik definition consists of:

Example

An example showing how to create a counter component:

export interface CounterProps {
  initialValue?: number;
  step?: number;
}
export const Counter = component$((props: CounterProps) => {
  const state = useStore({ count: props.initialValue || 0 });
  return (
    <div>
      <span>{state.count}</span>
      <button onClick$={() => (state.count += props.step || 1)}>+</button>
    </div>
  );
});
  • component$ is how a component gets declared. - { value?: number; step?: number } declares the public (props) interface of the component. - { count: number } declares the private (state) interface of the component.

The above can then be used like so:

export const OtherComponent = component$(() => {
  return <Counter initialValue={100} />;
});

See also: component, useCleanup, onResume, onPause, useOn, useOnDocument, useOnWindow, useStyles

component$: <PROPS = unknown>(onMount: OnRenderFn<PROPS>) => Component<PROPS>;

Parameter

Type

Description

onMount

OnRenderFn<PROPS>

Component<PROPS>

Edit this section

ComponentBaseProps

export interface ComponentBaseProps

Property

Modifiers

Type

Description

"q:slot"?

string

(Optional)

key?

string | number | null | undefined

(Optional)

Edit this section

ComputedFn

export type ComputedFn<T> = () => T;

Edit this section

ComputedSignal

A computed signal is a signal which is calculated from other signals. When the signals change, the computed signal is recalculated, and if the result changed, all tasks which are tracking the signal will be re-run and all components that read the signal will be re-rendered.

export interface ComputedSignal<T> extends ReadonlySignal<T>

Extends: ReadonlySignal<T>

Method

Description

force()

Use this to force recalculation and running subscribers, for example when the calculated value mutates but remains the same object. Useful for third-party libraries.

Edit this section

ContextId

ContextId is a typesafe ID for your context.

Context is a way to pass stores to the child components without prop-drilling.

Use createContextId() to create a ContextId. A ContextId is just a serializable identifier for the context. It is not the context value itself. See useContextProvider() and useContext() for the values. Qwik needs a serializable ID for the context so that the it can track context providers and consumers in a way that survives resumability.

Example

// Declare the Context type.
interface TodosStore {
  items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
 
// Example of providing context to child components.
export const App = component$(() => {
  useContextProvider(
    TodosContext,
    useStore<TodosStore>({
      items: ["Learn Qwik", "Build Qwik app", "Profit"],
    }),
  );
 
  return <Items />;
});
 
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
  const todos = useContext(TodosContext);
  return (
    <ul>
      {todos.items.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
  );
});
export interface ContextId<STATE>

Property

Modifiers

Type

Description

__brand_context_type__

readonly

STATE

Design-time property to store type information for the context.

id

readonly

string

A unique ID for the context.

Edit this section

CorePlatform

Low-level API for platform abstraction.

Different platforms (browser, node, service workers) may have different ways of handling things such as requestAnimationFrame and imports. To make Qwik platform-independent Qwik uses the CorePlatform API to access the platform API.

CorePlatform also is responsible for importing symbols. The import map is different on the client (browser) then on the server. For this reason, the server has a manifest that is used to map symbols to javascript chunks. The manifest is encapsulated in CorePlatform, for this reason, the CorePlatform can't be global as there may be multiple applications running at server concurrently.

This is a low-level API and there should not be a need for you to access this.

export interface CorePlatform

Property

Modifiers

Type

Description

chunkForSymbol

(symbolName: string, chunk: string | null, parent?: string) => readonly [symbol: string, chunk: string] | undefined

Retrieve chunk name for the symbol.

When the application is running on the server the symbols may be imported from different files (as server build is typically a single javascript chunk.) For this reason, it is necessary to convert the chunks from server format to client (browser) format. This is done by looking up symbols (which are globally unique) in the manifest. (Manifest is the mapping of symbols to the client chunk names.)

importSymbol

(containerEl: Element | undefined, url: string | URL | undefined | null, symbol: string) => ValueOrPromise<any>

Retrieve a symbol value from QRL.

Qwik needs to lazy load data and closures. For this Qwik uses QRLs that are serializable references of resources that are needed. The QRLs contain all the information necessary to retrieve the reference using importSymbol.

Why not use import()? Because import() is relative to the current file, and the current file is always the Qwik framework. So QRLs have additional information that allows them to serialize imports relative to application base rather than the Qwik framework file.

isServer

boolean

True of running on the server platform.

nextTick

(fn: () => any) => Promise<any>

Perform operation on next tick.

raf

(fn: () => any) => Promise<any>

Perform operation on next request-animation-frame.

Edit this section

CorrectedToggleEvent

This corrects the TS definition for ToggleEvent

export interface CorrectedToggleEvent extends Event

Extends: Event

Property

Modifiers

Type

Description

newState

readonly

'open' | 'closed'

prevState

readonly

'open' | 'closed'

Edit this section

createComputed$

Create a computed signal which is calculated from the given QRL. A computed signal is a signal which is calculated from other signals. When the signals change, the computed signal is recalculated.

The QRL must be a function which returns the value of the signal. The function must not have side effects, and it mus be synchronous.

If you need the function to be async, use useSignal and useTask$ instead.

createComputed$: <T>(qrl: () => T) => T extends Promise<any> ? never : ComputedSignal<T>

Parameter

Type

Description

qrl

() => T

T extends Promise<any> ? never : ComputedSignal<T>

Edit this section

createContextId

Create a context ID to be used in your application. The name should be written with no spaces.

Context is a way to pass stores to the child components without prop-drilling.

Use createContextId() to create a ContextId. A ContextId is just a serializable identifier for the context. It is not the context value itself. See useContextProvider() and useContext() for the values. Qwik needs a serializable ID for the context so that the it can track context providers and consumers in a way that survives resumability.

Example

// Declare the Context type.
interface TodosStore {
  items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
 
// Example of providing context to child components.
export const App = component$(() => {
  useContextProvider(
    TodosContext,
    useStore<TodosStore>({
      items: ["Learn Qwik", "Build Qwik app", "Profit"],
    }),
  );
 
  return <Items />;
});
 
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
  const todos = useContext(TodosContext);
  return (
    <ul>
      {todos.items.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
  );
});
createContextId: <STATE = unknown>(name: string) => ContextId<STATE>;

Parameter

Type

Description

name

string

The name of the context.

ContextId<STATE>

Edit this section

createSignal

Creates a Signal with the given value. If no value is given, the signal is created with undefined.

createSignal: {
    <T>(): Signal<T | undefined>;
    <T>(value: T): Signal<T>;
}

Edit this section

DevJSX

export interface DevJSX

Property

Modifiers

Type

Description

columnNumber

number

fileName

string

lineNumber

number

stack?

string

(Optional)

Edit this section

DOMAttributes

The Qwik-specific attributes that DOM elements accept

export interface DOMAttributes<EL extends Element> extends DOMAttributesBase<EL>, QwikEvents<EL>

Extends: DOMAttributesBase<EL>, QwikEvents<EL>

Property

Modifiers

Type

Description

class?

ClassList | Signal<ClassList> | undefined

(Optional)

Edit this section

EagernessOptions

export type EagernessOptions = "visible" | "load" | "idle";

Edit this section

Element

type Element = JSXOutput;

References: JSXOutput

ElementChildrenAttribute

interface ElementChildrenAttribute

Property

Modifiers

Type

Description

children

JSXChildren

ElementType

type ElementType = string | FunctionComponent<Record<any, any>>;

References: FunctionComponent

ErrorBoundaryStore

export interface ErrorBoundaryStore

Property

Modifiers

Type

Description

error

any | undefined

Edit this section

event$

event$: <T>(qrl: T) => import("./qrl.public").QRL<T>;

Parameter

Type

Description

qrl

T

import("./qrl.public").QRL<T>

Edit this section

EventHandler

A DOM event handler

export type EventHandler<EV = Event, EL = Element> = {
  bivarianceHack(event: EV, element: EL): any;
}["bivarianceHack"];

Edit this section

force

Use this to force recalculation and running subscribers, for example when the calculated value mutates but remains the same object. Useful for third-party libraries.

force(): void;

Returns:

void

Fragment

Fragment: FunctionComponent<{
  children?: any;
  key?: string | number | null;
}>;

Edit this section

FunctionComponent

Any function taking a props object that returns JSXOutput.

The key, flags and dev parameters are for internal use.

export type FunctionComponent<P = unknown> = {
  renderFn(
    props: P,
    key: string | null,
    flags: number,
    dev?: DevJSX,
  ): JSXOutput;
}["renderFn"];

References: DevJSX, JSXOutput

Edit this section

getDomContainer

export declare function getDomContainer(
  element: Element | VNode,
): IClientContainer;

Parameter

Type

Description

element

Element | VNode

IClientContainer

Edit this section

getLocale

Retrieve the current locale.

If no current locale and there is no defaultLocale the function throws an error.

export declare function getLocale(defaultLocale?: string): string;

Parameter

Type

Description

defaultLocale

string

(Optional)

string

The locale.

Edit this section

getPlatform

Retrieve the CorePlatform.

The CorePlatform is also responsible for retrieving the Manifest, that contains mappings from symbols to javascript import chunks. For this reason, CorePlatform can't be global, but is specific to the application currently running. On server it is possible that many different applications are running in a single server instance, and for this reason the CorePlatform is associated with the application document.

getPlatform: () => CorePlatform;

Returns:

CorePlatform

Edit this section

h

The legacy transform, used in special cases like <div {...props} key="key" />. Note that the children are spread arguments, instead of a prop like in jsx() calls.

Also note that this disables optimizations.

export declare function h<
  TYPE extends string | FunctionComponent<PROPS>,
  PROPS extends {} = {},
>(type: TYPE, props?: PROPS | null, ...children: any[]): JSXNode<TYPE>;

Parameter

Type

Description

type

TYPE

props

PROPS | null

(Optional)

children

any[]

JSXNode<TYPE>

Edit this section

implicit$FirstArg

Create a ____$(...) convenience method from ___(...).

It is very common for functions to take a lazy-loadable resource as a first argument. For this reason, the Qwik Optimizer automatically extracts the first argument from any function which ends in $.

This means that foo$(arg0) and foo($(arg0)) are equivalent with respect to Qwik Optimizer. The former is just a shorthand for the latter.

For example, these function calls are equivalent:

  • component$(() => {...}) is same as component($(() => {...}))
export function myApi(callback: QRL<() => void>): void {
  // ...
}
 
export const myApi$ = implicit$FirstArg(myApi);
// type of myApi$: (callback: () => void): void
 
// can be used as:
myApi$(() => console.log("callback"));
 
// will be transpiled to:
// FILE: <current file>
myApi(qrl("./chunk-abc.js", "callback"));
 
// FILE: chunk-abc.js
export const callback = () => console.log("callback");
implicit$FirstArg: <FIRST, REST extends any[], RET>(
    fn: (qrl: QRL<FIRST>, ...rest: REST) => RET,
  ) =>
  (qrl: FIRST, ...rest: REST) =>
    RET;

Parameter

Type

Description

fn

(qrl: QRL<FIRST>, ...rest: REST) => RET

A function that should have its first argument automatically $.

((qrl: FIRST, ...rest: REST) => RET)

Edit this section

IntrinsicAttributes

interface IntrinsicAttributes extends QwikIntrinsicAttributes

Extends: QwikIntrinsicAttributes

IntrinsicElements

interface IntrinsicElements extends LenientQwikElements

Extends: LenientQwikElements

isSignal

isSignal: (value: any) => value is ISignal<unknown>

Parameter

Type

Description

value

any

value is ISignal<unknown>

Edit this section

jsx

Used by the JSX transpilers to create a JSXNode. Note that the optimizer will not use this, instead using _jsxSplit and _jsxSorted directly.

jsx: <T extends string | FunctionComponent<any>>(
  type: T,
  props: T extends FunctionComponent<infer PROPS> ? PROPS : Props,
  key?: string | number | null,
) => JSXNode<T>;

Parameter

Type

Description

type

T

props

T extends FunctionComponent<infer PROPS> ? PROPS : Props

key

string | number | null

(Optional)

JSXNode<T>

Edit this section

JSXChildren

export type JSXChildren =
  | string
  | number
  | boolean
  | null
  | undefined
  | Function
  | RegExp
  | JSXChildren[]
  | Promise<JSXChildren>
  | Signal<JSXChildren>
  | JSXNode;

References: JSXChildren, Signal, JSXNode

Edit this section

jsxDEV

jsxDEV: <T extends string | FunctionComponent<Props>>(
  type: T,
  props: T extends FunctionComponent<infer PROPS> ? PROPS : Props,
  key: string | number | null | undefined,
  _isStatic: boolean,
  opts: JsxDevOpts,
  _ctx: unknown,
) => JSXNode<T>;

Parameter

Type

Description

type

T

props

T extends FunctionComponent<infer PROPS> ? PROPS : Props

key

string | number | null | undefined

_isStatic

boolean

opts

JsxDevOpts

_ctx

unknown

JSXNode<T>

Edit this section

JSXNode

A JSX Node, an internal structure. You probably want to use JSXOutput instead.

export interface JSXNode<T extends string | FunctionComponent | unknown = unknown>

Property

Modifiers

Type

Description

children

JSXChildren | null

dev?

DevJSX

(Optional)

key

string | null

props

T extends FunctionComponent<infer P> ? P : Record<any, unknown>

type

T

Edit this section

JSXOutput

Any valid output for a component

export type JSXOutput =
  | JSXNode
  | string
  | number
  | boolean
  | null
  | undefined
  | JSXOutput[];

References: JSXNode, JSXOutput

Edit this section

JSXTagName

export type JSXTagName =
  | keyof HTMLElementTagNameMap
  | Omit<string, keyof HTMLElementTagNameMap>;

Edit this section

KnownEventNames

The names of events that Qwik knows about. They are all lowercase, but on the JSX side, they are PascalCase for nicer DX. (onAuxClick$ vs onauxclick$)

export type KnownEventNames = LiteralUnion<AllEventKeys, string>;

Edit this section

NativeAnimationEvent

Warning: This API is now obsolete.

Use AnimationEvent and use the second argument to the handler function for the current event target

export type NativeAnimationEvent = AnimationEvent;

Edit this section

NativeClipboardEvent

Warning: This API is now obsolete.

Use ClipboardEvent and use the second argument to the handler function for the current event target

export type NativeClipboardEvent = ClipboardEvent;

Edit this section

NativeCompositionEvent

Warning: This API is now obsolete.

Use CompositionEvent and use the second argument to the handler function for the current event target

export type NativeCompositionEvent = CompositionEvent;

Edit this section

NativeDragEvent

Warning: This API is now obsolete.

Use DragEvent and use the second argument to the handler function for the current event target

export type NativeDragEvent = DragEvent;

Edit this section

NativeFocusEvent

Warning: This API is now obsolete.

Use FocusEvent and use the second argument to the handler function for the current event target

export type NativeFocusEvent = FocusEvent;

Edit this section

NativeKeyboardEvent

Warning: This API is now obsolete.

Use KeyboardEvent and use the second argument to the handler function for the current event target

export type NativeKeyboardEvent = KeyboardEvent;

Edit this section

NativeMouseEvent

Warning: This API is now obsolete.

Use MouseEvent and use the second argument to the handler function for the current event target

export type NativeMouseEvent = MouseEvent;

Edit this section

NativePointerEvent

Warning: This API is now obsolete.

Use PointerEvent and use the second argument to the handler function for the current event target

export type NativePointerEvent = PointerEvent;

Edit this section

NativeTouchEvent

Warning: This API is now obsolete.

Use TouchEvent and use the second argument to the handler function for the current event target

export type NativeTouchEvent = TouchEvent;

Edit this section

NativeTransitionEvent

Warning: This API is now obsolete.

Use TransitionEvent and use the second argument to the handler function for the current event target

export type NativeTransitionEvent = TransitionEvent;

Edit this section

NativeUIEvent

Warning: This API is now obsolete.

Use UIEvent and use the second argument to the handler function for the current event target

export type NativeUIEvent = UIEvent;

Edit this section

NativeWheelEvent

Warning: This API is now obsolete.

Use WheelEvent and use the second argument to the handler function for the current event target

export type NativeWheelEvent = WheelEvent;

Edit this section

noSerialize

Returned type of the noSerialize() function. It will be TYPE or undefined.

export type NoSerialize<T> =
  | (T & {
      __no_serialize__: true;
    })
  | undefined;

Edit this section

NoSerialize

Returned type of the noSerialize() function. It will be TYPE or undefined.

export type NoSerialize<T> =
  | (T & {
      __no_serialize__: true;
    })
  | undefined;

Edit this section

OnRenderFn

export type OnRenderFn<PROPS> = (props: PROPS) => JSXOutput;

References: JSXOutput

Edit this section

OnVisibleTaskOptions

export interface OnVisibleTaskOptions

Property

Modifiers

Type

Description

strategy?

VisibleTaskStrategy

(Optional) The strategy to use to determine when the "VisibleTask" should first execute.

  • intersection-observer: the task will first execute when the element is visible in the viewport, under the hood it uses the IntersectionObserver API. - document-ready: the task will first execute when the document is ready, under the hood it uses the document load event. - document-idle: the task will first execute when the document is idle, under the hood it uses the requestIdleCallback API.

Edit this section

PrefetchGraph

This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Load the prefetch graph for the container.

Each Qwik container needs to include its own prefetch graph.

PrefetchGraph: (opts?: {
  base?: string;
  manifestHash?: string;
  manifestURL?: string;
  nonce?: string;
}) => JSXOutput;

Parameter

Type

Description

opts

{ base?: string; manifestHash?: string; manifestURL?: string; nonce?: string; }

(Optional) Options for the loading prefetch graph.

  • base - Base of the graph. For a default installation this will default to the q:base value /build/. But if more than one MFE is installed on the page, then each MFE needs to have its own base. - manifestHash - Hash of the manifest file to load. If not provided the hash will be extracted from the container attribute q:manifest-hash and assume the default build file ${base}/q-bundle-graph-${manifestHash}.json. - manifestURL - URL of the manifest file to load if non-standard bundle graph location name.

JSXOutput

Edit this section

PrefetchServiceWorker

This API is provided as a beta preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Install a service worker which will prefetch the bundles.

There can only be one service worker per page. Because there can be many separate Qwik Containers on the page each container needs to load its prefetch graph using PrefetchGraph component.

PrefetchServiceWorker: (opts: {
  base?: string;
  scope?: string;
  path?: string;
  verbose?: boolean;
  fetchBundleGraph?: boolean;
  nonce?: string;
}) => JSXOutput;

Parameter

Type

Description

opts

{ base?: string; scope?: string; path?: string; verbose?: boolean; fetchBundleGraph?: boolean; nonce?: string; }

Options for the prefetch service worker.

  • base - Base URL for the service worker. Default is import.meta.env.BASE_URL, which is defined by Vite's config.base and defaults to /. - scope - Base URL for when the service-worker will activate. Default is / - path - Path to the service worker. Default is qwik-prefetch-service-worker.js unless you pass a path that starts with a / then the base is ignored. Default is qwik-prefetch-service-worker.js - verbose - Verbose logging for the service worker installation. Default is false - nonce - Optional nonce value for security purposes, defaults to undefined.

JSXOutput

Edit this section

PropFunction

Alias for QRL<T>. Of historic relevance only.

export type PropFunction<T> = QRL<T>;

References: QRL

Edit this section

PropsOf

Infers Props from the component or tag.

export type PropsOf<COMP> = COMP extends string
  ? COMP extends keyof QwikIntrinsicElements
    ? QwikIntrinsicElements[COMP]
    : QwikIntrinsicElements["span"]
  : NonNullable<COMP> extends never
    ? never
    : COMP extends FunctionComponent<infer PROPS>
      ? PROPS extends Record<any, infer V>
        ? IsAny<V> extends true
          ? never
          : ObjectProps<PROPS>
        : COMP extends Component<infer OrigProps>
          ? ObjectProps<OrigProps>
          : PROPS
      : never;

References: QwikIntrinsicElements, FunctionComponent, Component

const Desc = component$(
  ({ desc, ...props }: { desc: string } & PropsOf<"div">) => {
    return <div {...props}>{desc}</div>;
  },
);
 
const TitleBox = component$(
  ({ title, ...props }: { title: string } & PropsOf<Box>) => {
    return (
      <Box {...props}>
        <h1>{title}</h1>
      </Box>
    );
  },
);

Edit this section

PublicProps

Extends the defined component PROPS, adding the default ones (children and q:slot) and allowing plain functions to QRL arguments.

export type PublicProps<PROPS> = (PROPS extends Record<any, any>
  ? Omit<PROPS, `${string}$`> & _Only$<PROPS>
  : unknown extends PROPS
    ? {}
    : PROPS) &
  ComponentBaseProps &
  ComponentChildren<PROPS>;

References: ComponentBaseProps

Edit this section

qrl

The QRL type represents a lazy-loadable AND serializable resource.

QRL stands for Qwik URL.

Use QRL when you want to refer to a lazy-loaded resource. QRLs are most often used for code (functions) but can also be used for other resources such as strings in the case of styles.

QRL is an opaque token that is generated by the Qwik Optimizer. (Do not rely on any properties in QRL as it may change between versions.)

## Creating QRL references

Creating QRL is done using $(...) function. $(...) is a special marker for the Qwik Optimizer that marks that the code should be extracted into a lazy-loaded symbol.

useOnDocument(
  "mousemove",
  $((event) => console.log("mousemove", event)),
);

In the above code, the Qwik Optimizer detects $(...) and transforms the code as shown below:

// FILE: <current file>
useOnDocument("mousemove", qrl("./chunk-abc.js", "onMousemove"));
 
// FILE: chunk-abc.js
export const onMousemove = () => console.log("mousemove");

NOTE: qrl(...) is a result of Qwik Optimizer transformation. You should never have to invoke this function directly in your application. The qrl(...) function should be invoked only after the Qwik Optimizer transformation.

## Using QRLs

Use QRL type in your application when you want to get a lazy-loadable reference to a resource (most likely a function).

// Example of declaring a custom functions which takes callback as QRL.
export function useMyFunction(callback: QRL<() => void>) {
  doExtraStuff();
  // The callback passed to `onDocument` requires `QRL`.
  useOnDocument("mousemove", callback);
}

In the above example, the way to think about the code is that you are not asking for a callback function but rather a reference to a lazy-loadable callback function. Specifically, the function loading should be delayed until it is actually needed. In the above example, the function would not load until after a mousemove event on document fires.

## Resolving QRL references

At times it may be necessary to resolve a QRL reference to the actual value. This can be performed using QRL.resolve(..) function.

// Assume you have QRL reference to a greet function
const lazyGreet: QRL<() => void> = $(() => console.log("Hello World!"));
 
// Use `qrlImport` to load / resolve the reference.
const greet: () => void = await lazyGreet.resolve();
 
//  Invoke it
greet();

NOTE: element is needed because QRLs are relative and need a base location to resolve against. The base location is encoded in the HTML in the form of <div q:base="/url">.

## QRL.resolved

Once QRL.resolve() returns, the value is stored under QRL.resolved. This allows the value to be used without having to await QRL.resolve() again.

## Question: Why not just use import()?

At first glance, QRL serves the same purpose as import(). However, there are three subtle differences that need to be taken into account.

  1. QRLs must be serializable into HTML. 2. QRLs must be resolved by framework relative to q:base. 3. QRLs must be able to capture lexically scoped variables. 4. QRLs encapsulate the difference between running with and without Qwik Optimizer. 5. QRLs allow expressing lazy-loaded boundaries without thinking about chunk and symbol names.

Let's assume that you intend to write code such as this:

return <button onClick={() => (await import('./chunk-abc.js')).onClick}>

The above code needs to be serialized into DOM such as:

<div q:base="/build/">
  <button on:click="./chunk-abc.js#onClick">...</button>
</div>
  1. Notice there is no easy way to extract chunk (./chunk-abc.js) and symbol (onClick) into HTML. 2. Notice that even if you could extract it, the import('./chunk-abc.js') would become relative to where the import() file is declared. Because it is our framework doing the load, the ./chunk-abc.js would become relative to the framework file. This is not correct, as it should be relative to the original file generated by the bundler. 3. Next, the framework needs to resolve the ./chunk-abc.js and needs a base location that is encoded in the HTML. 4. The QRL needs to be able to capture lexically scoped variables. (import() only allows loading top-level symbols which don't capture variables.) 5. As a developer, you don't want to think about import and naming the chunks and symbols. You just want to say: "this should be lazy."

These are the main reasons why Qwik introduces its own concept of QRL.

export type QRL<TYPE = unknown> = {
  __qwik_serializable__?: any;
  __brand__QRL__: TYPE;
  resolve(): Promise<TYPE>;
  resolved: undefined | TYPE;
  getCaptured(): unknown[] | null;
  getSymbol(): string;
  getHash(): string;
  dev: QRLDev | null;
} & BivariantQrlFn<QrlArgs<TYPE>, QrlReturn<TYPE>>;

Edit this section

QRL

The QRL type represents a lazy-loadable AND serializable resource.

QRL stands for Qwik URL.

Use QRL when you want to refer to a lazy-loaded resource. QRLs are most often used for code (functions) but can also be used for other resources such as strings in the case of styles.

QRL is an opaque token that is generated by the Qwik Optimizer. (Do not rely on any properties in QRL as it may change between versions.)

## Creating QRL references

Creating QRL is done using $(...) function. $(...) is a special marker for the Qwik Optimizer that marks that the code should be extracted into a lazy-loaded symbol.

useOnDocument(
  "mousemove",
  $((event) => console.log("mousemove", event)),
);

In the above code, the Qwik Optimizer detects $(...) and transforms the code as shown below:

// FILE: <current file>
useOnDocument("mousemove", qrl("./chunk-abc.js", "onMousemove"));
 
// FILE: chunk-abc.js
export const onMousemove = () => console.log("mousemove");

NOTE: qrl(...) is a result of Qwik Optimizer transformation. You should never have to invoke this function directly in your application. The qrl(...) function should be invoked only after the Qwik Optimizer transformation.

## Using QRLs

Use QRL type in your application when you want to get a lazy-loadable reference to a resource (most likely a function).

// Example of declaring a custom functions which takes callback as QRL.
export function useMyFunction(callback: QRL<() => void>) {
  doExtraStuff();
  // The callback passed to `onDocument` requires `QRL`.
  useOnDocument("mousemove", callback);
}

In the above example, the way to think about the code is that you are not asking for a callback function but rather a reference to a lazy-loadable callback function. Specifically, the function loading should be delayed until it is actually needed. In the above example, the function would not load until after a mousemove event on document fires.

## Resolving QRL references

At times it may be necessary to resolve a QRL reference to the actual value. This can be performed using QRL.resolve(..) function.

// Assume you have QRL reference to a greet function
const lazyGreet: QRL<() => void> = $(() => console.log("Hello World!"));
 
// Use `qrlImport` to load / resolve the reference.
const greet: () => void = await lazyGreet.resolve();
 
//  Invoke it
greet();

NOTE: element is needed because QRLs are relative and need a base location to resolve against. The base location is encoded in the HTML in the form of <div q:base="/url">.

## QRL.resolved

Once QRL.resolve() returns, the value is stored under QRL.resolved. This allows the value to be used without having to await QRL.resolve() again.

## Question: Why not just use import()?

At first glance, QRL serves the same purpose as import(). However, there are three subtle differences that need to be taken into account.

  1. QRLs must be serializable into HTML. 2. QRLs must be resolved by framework relative to q:base. 3. QRLs must be able to capture lexically scoped variables. 4. QRLs encapsulate the difference between running with and without Qwik Optimizer. 5. QRLs allow expressing lazy-loaded boundaries without thinking about chunk and symbol names.

Let's assume that you intend to write code such as this:

return <button onClick={() => (await import('./chunk-abc.js')).onClick}>

The above code needs to be serialized into DOM such as:

<div q:base="/build/">
  <button on:click="./chunk-abc.js#onClick">...</button>
</div>
  1. Notice there is no easy way to extract chunk (./chunk-abc.js) and symbol (onClick) into HTML. 2. Notice that even if you could extract it, the import('./chunk-abc.js') would become relative to where the import() file is declared. Because it is our framework doing the load, the ./chunk-abc.js would become relative to the framework file. This is not correct, as it should be relative to the original file generated by the bundler. 3. Next, the framework needs to resolve the ./chunk-abc.js and needs a base location that is encoded in the HTML. 4. The QRL needs to be able to capture lexically scoped variables. (import() only allows loading top-level symbols which don't capture variables.) 5. As a developer, you don't want to think about import and naming the chunks and symbols. You just want to say: "this should be lazy."

These are the main reasons why Qwik introduces its own concept of QRL.

export type QRL<TYPE = unknown> = {
  __qwik_serializable__?: any;
  __brand__QRL__: TYPE;
  resolve(): Promise<TYPE>;
  resolved: undefined | TYPE;
  getCaptured(): unknown[] | null;
  getSymbol(): string;
  getHash(): string;
  dev: QRLDev | null;
} & BivariantQrlFn<QrlArgs<TYPE>, QrlReturn<TYPE>>;

Edit this section

QRLEventHandlerMulti

An event handler for Qwik events, can be a handler QRL or an array of handler QRLs.

export type QRLEventHandlerMulti<EV extends Event, EL> =
  | QRL<EventHandler<EV, EL>>
  | undefined
  | null
  | QRLEventHandlerMulti<EV, EL>[]
  | EventHandler<EV, EL>;

References: QRL, EventHandler, QRLEventHandlerMulti

Edit this section

QwikAnimationEvent

Warning: This API is now obsolete.

Use AnimationEvent and use the second argument to the handler function for the current event target

export type QwikAnimationEvent<T = Element> = NativeAnimationEvent;

References: NativeAnimationEvent

Edit this section

QwikAttributes

The Qwik DOM attributes without plain handlers, for use as function parameters

export interface QwikAttributes<EL extends Element> extends DOMAttributesBase<EL>, QwikEvents<EL, false>

Extends: DOMAttributesBase<EL>, QwikEvents<EL, false>

Property

Modifiers

Type

Description

class?

ClassList | undefined

(Optional)

Edit this section

QwikChangeEvent

Warning: This API is now obsolete.

Use Event and use the second argument to the handler function for the current event target. Also note that in Qwik, onInput$ with the InputEvent is the event that behaves like onChange in React.

export type QwikChangeEvent<T = Element> = Event;

Edit this section

QwikClipboardEvent

Warning: This API is now obsolete.

Use ClipboardEvent and use the second argument to the handler function for the current event target

export type QwikClipboardEvent<T = Element> = NativeClipboardEvent;

References: NativeClipboardEvent

Edit this section

QwikCompositionEvent

Warning: This API is now obsolete.

Use CompositionEvent and use the second argument to the handler function for the current event target

export type QwikCompositionEvent<T = Element> = NativeCompositionEvent;

References: NativeCompositionEvent

Edit this section

QwikDOMAttributes

export interface QwikDOMAttributes extends DOMAttributes<Element>

Extends: DOMAttributes<Element>

Edit this section

QwikDragEvent

Warning: This API is now obsolete.

Use DragEvent and use the second argument to the handler function for the current event target

export type QwikDragEvent<T = Element> = NativeDragEvent;

References: NativeDragEvent

Edit this section

QwikFocusEvent

Warning: This API is now obsolete.

Use FocusEvent and use the second argument to the handler function for the current event target

export type QwikFocusEvent<T = Element> = NativeFocusEvent;

References: NativeFocusEvent

Edit this section

QwikHTMLElements

The DOM props without plain handlers, for use inside functions

export type QwikHTMLElements = {
  [tag in keyof HTMLElementTagNameMap]: Augmented<
    HTMLElementTagNameMap[tag],
    SpecialAttrs[tag]
  > &
    HTMLElementAttrs &
    QwikAttributes<HTMLElementTagNameMap[tag]>;
};

References: QwikAttributes

Edit this section

QwikIdleEvent

Emitted by qwik-loader on document when the document first becomes idle

export type QwikIdleEvent = CustomEvent<{}>;

Edit this section

QwikInitEvent

Emitted by qwik-loader on document when the document first becomes interactive

export type QwikInitEvent = CustomEvent<{}>;

Edit this section

QwikIntrinsicElements

The interface holds available attributes of both native DOM elements and custom Qwik elements. An example showing how to define a customizable wrapper component:

import { component$, Slot, type QwikIntrinsicElements } from "@qwik.dev/core";
 
type WrapperProps = {
  attributes?: QwikIntrinsicElements["div"];
};
 
export default component$<WrapperProps>(({ attributes }) => {
  return (
    <div {...attributes} class="p-2">
      <Slot />
    </div>
  );
});

Note: It is shorter to use PropsOf<'div'>

export interface QwikIntrinsicElements extends QwikHTMLElements, QwikSVGElements

Extends: QwikHTMLElements, QwikSVGElements

Edit this section

QwikInvalidEvent

Warning: This API is now obsolete.

Use Event and use the second argument to the handler function for the current event target

export type QwikInvalidEvent<T = Element> = Event;

Edit this section

QwikJSX

export declare namespace QwikJSX

Interface

Description

ElementChildrenAttribute

IntrinsicAttributes

IntrinsicElements

Type Alias

Description

Element

ElementType

Edit this section

QwikKeyboardEvent

Warning: This API is now obsolete.

Use KeyboardEvent and use the second argument to the handler function for the current event target

export type QwikKeyboardEvent<T = Element> = NativeKeyboardEvent;

References: NativeKeyboardEvent

Edit this section

QwikMouseEvent

Warning: This API is now obsolete.

Use MouseEvent and use the second argument to the handler function for the current event target

export type QwikMouseEvent<T = Element, E = NativeMouseEvent> = E;

References: NativeMouseEvent

Edit this section

QwikPointerEvent

Warning: This API is now obsolete.

Use PointerEvent and use the second argument to the handler function for the current event target

export type QwikPointerEvent<T = Element> = NativePointerEvent;

References: NativePointerEvent

Edit this section

QwikSubmitEvent

Warning: This API is now obsolete.

Use SubmitEvent and use the second argument to the handler function for the current event target

export type QwikSubmitEvent<T = Element> = SubmitEvent;

Edit this section

QwikSVGElements

The SVG props without plain handlers, for use inside functions

export type QwikSVGElements = {
  [K in keyof Omit<
    SVGElementTagNameMap,
    keyof HTMLElementTagNameMap
  >]: SVGProps<SVGElementTagNameMap[K]>;
};

Edit this section

QwikSymbolEvent

Emitted by qwik-loader when a module was lazily loaded

export type QwikSymbolEvent = CustomEvent<{
  qBase: string;
  qManifest: string;
  qVersion: string;
  href: string;
  symbol: string;
  element: Element;
  reqTime: number;
}>;

Edit this section

QwikTouchEvent

Warning: This API is now obsolete.

Use TouchEvent and use the second argument to the handler function for the current event target

export type QwikTouchEvent<T = Element> = NativeTouchEvent;

References: NativeTouchEvent

Edit this section

QwikTransitionEvent

Warning: This API is now obsolete.

Use TransitionEvent and use the second argument to the handler function for the current event target

export type QwikTransitionEvent<T = Element> = NativeTransitionEvent;

References: NativeTransitionEvent

Edit this section

QwikUIEvent

Warning: This API is now obsolete.

Use UIEvent and use the second argument to the handler function for the current event target

export type QwikUIEvent<T = Element> = NativeUIEvent;

References: NativeUIEvent

Edit this section

QwikVisibleEvent

Emitted by qwik-loader when an element becomes visible. Used by useVisibleTask$

export type QwikVisibleEvent = CustomEvent<IntersectionObserverEntry>;

Edit this section

QwikWheelEvent

Warning: This API is now obsolete.

Use WheelEvent and use the second argument to the handler function for the current event target

export type QwikWheelEvent<T = Element> = NativeWheelEvent;

References: NativeWheelEvent

Edit this section

ReadonlySignal

export interface ReadonlySignal<T = unknown>

Property

Modifiers

Type

Description

value

readonly

T

Edit this section

render

Render JSX.

Use this method to render JSX. This function does reconciling which means it always tries to reuse what is already in the DOM (rather then destroy and recreate content.) It returns a cleanup function you could use for cleaning up subscriptions.

render: (
  parent: Element | Document,
  jsxNode: JSXOutput | FunctionComponent<any>,
  opts?: RenderOptions,
) => Promise<RenderResult>;

Parameter

Type

Description

parent

Element | Document

Element which will act as a parent to jsxNode. When possible the rendering will try to reuse existing nodes.

jsxNode

JSXOutput | FunctionComponent<any>

JSX to render

opts

RenderOptions

(Optional)

Promise<RenderResult>

An object containing a cleanup function.

Edit this section

RenderOnce

RenderOnce: FunctionComponent<{
  children?: unknown;
  key?: string | number | null | undefined;
}>;

Edit this section

RenderOptions

export interface RenderOptions

Property

Modifiers

Type

Description

serverData?

Record<string, any>

(Optional)

Edit this section

RenderResult

export interface RenderResult

Method

Description

cleanup()

Edit this section

RenderSSROptions

export interface RenderSSROptions

Property

Modifiers

Type

Description

base?

string

(Optional)

containerAttributes

Record<string, string>

containerTagName

string

manifestHash

string

serverData?

Record<string, any>

(Optional)

stream

StreamWriter

Edit this section

Resource

This method works like an async memoized function that runs whenever some tracked value changes and returns some data.

useResource however returns immediate a ResourceReturn object that contains the data and a state that indicates if the data is available or not.

The status can be one of the following:

  • pending - the data is not yet available. - resolved - the data is available. - rejected - the data is not available due to an error or timeout.

Be careful when using a try/catch statement in useResource$. If you catch the error and don't re-throw it (or a new Error), the resource status will never be rejected.

Example

Example showing how useResource to perform a fetch to request the weather, whenever the input city name changes.

const Cmp = component$(() => {
  const cityS = useSignal("");
 
  const weatherResource = useResource$(async ({ track, cleanup }) => {
    const cityName = track(cityS);
    const abortController = new AbortController();
    cleanup(() => abortController.abort("cleanup"));
    const res = await fetch(`http://weatherdata.com?city=${cityName}`, {
      signal: abortController.signal,
    });
    const data = await res.json();
    return data as { temp: number };
  });
 
  return (
    <div>
      <input name="city" bind:value={cityS} />
      <Resource
        value={weatherResource}
        onResolved={(weather) => {
          return <div>Temperature: {weather.temp}</div>;
        }}
      />
    </div>
  );
});
Resource: <T>(props: ResourceProps<T>) => JSXOutput;

Parameter

Type

Description

props

ResourceProps<T>

JSXOutput

Edit this section

ResourceCtx

export interface ResourceCtx<T>

Property

Modifiers

Type

Description

previous

readonly

T | undefined

track

readonly

Tracker

Method

Description

cache(policyOrMilliseconds)

cleanup(callback)

Edit this section

ResourceFn

export type ResourceFn<T> = (ctx: ResourceCtx<unknown>) => ValueOrPromise<T>;

References: ResourceCtx, ValueOrPromise

Edit this section

ResourceOptions

Options to pass to useResource$()

export interface ResourceOptions

Property

Modifiers

Type

Description

timeout?

number

(Optional) Timeout in milliseconds. If the resource takes more than the specified millisecond, it will timeout. Resulting on a rejected resource.

Edit this section

ResourcePending

export interface ResourcePending<T>

Property

Modifiers

Type

Description

loading

readonly

boolean

value

readonly

Promise<T>

Edit this section

ResourceProps

export interface ResourceProps<T>

Property

Modifiers

Type

Description

onPending?

() => JSXOutput

(Optional)

onRejected?

(reason: Error) => JSXOutput

(Optional)

onResolved

(value: T) => JSXOutput

value

readonly

ResourceReturn<T> | Signal<Promise<T> | T> | Promise<T>

Edit this section

ResourceRejected

export interface ResourceRejected<T>

Property

Modifiers

Type

Description

loading

readonly

boolean

value

readonly

Promise<T>

Edit this section

ResourceResolved

export interface ResourceResolved<T>

Property

Modifiers

Type

Description

loading

readonly

boolean

value

readonly

Promise<T>

Edit this section

ResourceReturn

export type ResourceReturn<T> =
  | ResourcePending<T>
  | ResourceResolved<T>
  | ResourceRejected<T>;

References: ResourcePending, ResourceResolved, ResourceRejected

Edit this section

setPlatform

Sets the CorePlatform.

This is useful to override the platform in tests to change the behavior of, requestAnimationFrame, and import resolution.

setPlatform: (plt: CorePlatform) => CorePlatform;

Parameter

Type

Description

plt

CorePlatform

CorePlatform

Edit this section

Signal

A signal is a reactive value which can be read and written. When the signal is written, all tasks which are tracking the signal will be re-run and all components that read the signal will be re-rendered.

Furthermore, when a signal value is passed as a prop to a component, the optimizer will automatically forward the signal. This means that return <div title={signal.value}>hi</div> will update the title attribute when the signal changes without having to re-render the component.

export interface Signal<T = any> extends ReadonlySignal<T>

Extends: ReadonlySignal<T>

Property

Modifiers

Type

Description

value

T

Edit this section

SkipRender

SkipRender: JSXNode;

Edit this section

Slot

Allows to project the children of the current component. can only be used within the context of a component defined with component$.

Slot: FunctionComponent<{
  name?: string;
  children?: JSXChildren;
}>;

Edit this section

SnapshotListener

export interface SnapshotListener

Property

Modifiers

Type

Description

el

Element

key

string

qrl

QRL<any>

Edit this section

SnapshotMeta

export type SnapshotMeta = Record<string, SnapshotMetaValue>;

References: SnapshotMetaValue

Edit this section

SnapshotMetaValue

export interface SnapshotMetaValue

Property

Modifiers

Type

Description

c?

string

(Optional)

h?

string

(Optional)

s?

string

(Optional)

w?

string

(Optional)

Edit this section

SnapshotResult

export interface SnapshotResult

Property

Modifiers

Type

Description

funcs

string[]

mode

'render' | 'listeners' | 'static'

objs?

any[]

(Optional)

qrls

QRL[]

resources

ResourceReturnInternal<any>[]

state?

SnapshotState

(Optional)

Edit this section

SnapshotState

Warning: This API is now obsolete.

not longer used in v2

export interface SnapshotState

Property

Modifiers

Type

Description

ctx

SnapshotMeta

objs

any[]

refs

Record<string, string>

subs

any[]

Edit this section

SSRComment

SSRComment: FunctionComponent<{
  data: string;
}>;

Edit this section

SSRHintProps

export type SSRHintProps = {
  dynamic?: boolean;
};

Edit this section

SSRRaw

SSRRaw: FunctionComponent<{
  data: string;
}>;

Edit this section

SSRStream

SSRStream: FunctionComponent<SSRStreamProps>;

Edit this section

SSRStreamBlock

SSRStreamBlock: FunctionComponent<{
  children?: JSXOutput;
}>;

Edit this section

SSRStreamChildren

export type SSRStreamChildren =
  | AsyncGenerator<JSXChildren, void, any>
  | ((stream: StreamWriter) => Promise<void>)
  | (() => AsyncGenerator<JSXChildren, void, any>);

References: JSXChildren

Edit this section

SSRStreamProps

export type SSRStreamProps = {
  children: SSRStreamChildren;
};

References: SSRStreamChildren

Edit this section

sync$

Extract function into a synchronously loadable QRL.

NOTE: Synchronous QRLs functions can't close over any variables, including exports.

sync$: <T extends Function>(fn: T) => SyncQRL<T>;

Parameter

Type

Description

fn

T

Function to extract.

SyncQRL<T>

Edit this section

SyncQRL

export interface SyncQRL<TYPE extends Function = any> extends QRL<TYPE>

Extends: QRL<TYPE>

Property

Modifiers

Type

Description

__brand__SyncQRL__

TYPE

dev

QRLDev | null

resolved

TYPE

Edit this section

TaskCtx

export interface TaskCtx

Property

Modifiers

Type

Description

track

Tracker

Method

Description

cleanup(callback)

Edit this section

TaskFn

export type TaskFn = (ctx: TaskCtx) => ValueOrPromise<void | (() => void)>;

References: TaskCtx, ValueOrPromise

Edit this section

Tracker

Used to signal to Qwik which state should be watched for changes.

The Tracker is passed into the taskFn of useTask. It is intended to be used to wrap state objects in a read proxy which signals to Qwik which properties should be watched for changes. A change to any of the properties causes the taskFn to rerun.

Example

The obs passed into the taskFn is used to mark state.count as a property of interest. Any changes to the state.count property will cause the taskFn to rerun.

const Cmp = component$(() => {
  const store = useStore({ count: 0, doubleCount: 0 });
  const signal = useSignal(0);
  useTask$(({ track }) => {
    // Any signals or stores accessed inside the task will be tracked
    const count = track(() => store.count);
    // You can also pass a signal to track() directly
    const signalCount = track(signal);
    store.doubleCount = count + signalCount;
  });
  return (
    <div>
      <span>
        {store.count} / {store.doubleCount}
      </span>
      <button
        onClick$={() => {
          store.count++;
          signal.value++;
        }}
      >
        +
      </button>
    </div>
  );
});
export interface Tracker

Edit this section

untrack

Don't track listeners for this callback

untrack: <T>(fn: () => T) => T;

Parameter

Type

Description

fn

() => T

T

Edit this section

unwrapStore

Get the original object that was wrapped by the store. Useful if you want to clone a store (structuredClone, IndexedDB,...)

unwrapStore: <T>(value: T) => T;

Parameter

Type

Description

value

T

T

Edit this section

useComputed$

Creates a computed signal which is calculated from the given function. A computed signal is a signal which is calculated from other signals. When the signals change, the computed signal is recalculated, and if the result changed, all tasks which are tracking the signal will be re-run and all components that read the signal will be re-rendered.

The function must be synchronous and must not have any side effects.

useComputed$: <T>(qrl: import("./use-computed").ComputedFn<T>) => T extends Promise<any> ? never : import("..").ReadonlySignal<T>

Parameter

Type

Description

qrl

import("./use-computed").ComputedFn<T>

T extends Promise<any> ? never : import("..").ReadonlySignal<T>

Edit this section

useConstant

Stores a value which is retained for the lifetime of the component. Subsequent calls to useConstant will always return the first value given.

If the value is a function, the function is invoked once to calculate the actual value.

useConstant: <T>(value: (() => T) | T) => T;

Parameter

Type

Description

value

(() => T) | T

T

Edit this section

useContext

Retrieve Context value.

Use useContext() to retrieve the value of context in a component. To retrieve a value a parent component needs to invoke useContextProvider() to assign a value.

Example

// Declare the Context type.
interface TodosStore {
  items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
 
// Example of providing context to child components.
export const App = component$(() => {
  useContextProvider(
    TodosContext,
    useStore<TodosStore>({
      items: ["Learn Qwik", "Build Qwik app", "Profit"],
    }),
  );
 
  return <Items />;
});
 
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
  const todos = useContext(TodosContext);
  return (
    <ul>
      {todos.items.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
  );
});
useContext: UseContext;

Edit this section

useContextProvider

Assign a value to a Context.

Use useContextProvider() to assign a value to a context. The assignment happens in the component's function. Once assigned, use useContext() in any child component to retrieve the value.

Context is a way to pass stores to the child components without prop-drilling. Note that scalar values are allowed, but for reactivity you need signals or stores.

Example

// Declare the Context type.
interface TodosStore {
  items: string[];
}
// Create a Context ID (no data is saved here.)
// You will use this ID to both create and retrieve the Context.
export const TodosContext = createContextId<TodosStore>("Todos");
 
// Example of providing context to child components.
export const App = component$(() => {
  useContextProvider(
    TodosContext,
    useStore<TodosStore>({
      items: ["Learn Qwik", "Build Qwik app", "Profit"],
    }),
  );
 
  return <Items />;
});
 
// Example of retrieving the context provided by a parent component.
export const Items = component$(() => {
  const todos = useContext(TodosContext);
  return (
    <ul>
      {todos.items.map((item) => (
        <li>{item}</li>
      ))}
    </ul>
  );
});
useContextProvider: <STATE>(context: ContextId<STATE>, newValue: STATE) => void

Parameter

Type

Description

context

ContextId<STATE>

The context to assign a value to.

newValue

STATE

void

Edit this section

useErrorBoundary

useErrorBoundary: () => Readonly<ErrorBoundaryStore>;

Returns:

Readonly<ErrorBoundaryStore>

Edit this section

useId

useId: () => string;

Returns:

string

Edit this section

useOn

Register a listener on the current component's host element.

Used to programmatically add event listeners. Useful from custom use* methods, which do not have access to the JSX. Otherwise, it's adding a JSX listener in the <div> is a better idea.

useOn: <T extends KnownEventNames>(event: T | T[], eventQrl: EventQRL<T>) => void

Parameter

Type

Description

event

T | T[]

eventQrl

EventQRL<T>

void

Edit this section

useOnDocument

Register a listener on document.

Used to programmatically add event listeners. Useful from custom use* methods, which do not have access to the JSX.

useOnDocument: <T extends KnownEventNames>(event: T | T[], eventQrl: EventQRL<T>) => void

Parameter

Type

Description

event

T | T[]

eventQrl

EventQRL<T>

void

Edit this section

useOnWindow

Register a listener on window.

Used to programmatically add event listeners. Useful from custom use* methods, which do not have access to the JSX.

useOnWindow: <T extends KnownEventNames>(event: T | T[], eventQrl: EventQRL<T>) => void

Parameter

Type

Description

event

T | T[]

eventQrl

EventQRL<T>

void

Edit this section

useResource$

This method works like an async memoized function that runs whenever some tracked value changes and returns some data.

useResource however returns immediate a ResourceReturn object that contains the data and a state that indicates if the data is available or not.

The status can be one of the following:

  • pending - the data is not yet available. - resolved - the data is available. - rejected - the data is not available due to an error or timeout.

Be careful when using a try/catch statement in useResource$. If you catch the error and don't re-throw it (or a new Error), the resource status will never be rejected.

Example

Example showing how useResource to perform a fetch to request the weather, whenever the input city name changes.

const Cmp = component$(() => {
  const cityS = useSignal("");
 
  const weatherResource = useResource$(async ({ track, cleanup }) => {
    const cityName = track(cityS);
    const abortController = new AbortController();
    cleanup(() => abortController.abort("cleanup"));
    const res = await fetch(`http://weatherdata.com?city=${cityName}`, {
      signal: abortController.signal,
    });
    const data = await res.json();
    return data as { temp: number };
  });
 
  return (
    <div>
      <input name="city" bind:value={cityS} />
      <Resource
        value={weatherResource}
        onResolved={(weather) => {
          return <div>Temperature: {weather.temp}</div>;
        }}
      />
    </div>
  );
});
useResource$: <T>(generatorFn: ResourceFn<T>, opts?: ResourceOptions) =>
  ResourceReturn<T>;

Parameter

Type

Description

generatorFn

ResourceFn<T>

opts

ResourceOptions

(Optional)

ResourceReturn<T>

Edit this section

useServerData

export declare function useServerData<T>(key: string): T | undefined;

Parameter

Type

Description

key

string

T | undefined

Edit this section

useSignal

useSignal: UseSignal;

Edit this section

UseSignal

useSignal: UseSignal;

Edit this section

useStore

Creates an object that Qwik can track across serializations.

Use useStore to create a state for your application. The returned object is a proxy that has a unique ID. The ID of the object is used in the QRLs to refer to the store.

Example

Example showing how useStore is used in Counter example to keep track of the count.

const Stores = component$(() => {
  const counter = useCounter(1);
 
  // Reactivity happens even for nested objects and arrays
  const userData = useStore({
    name: "Manu",
    address: {
      address: "",
      city: "",
    },
    orgs: [],
  });
 
  // useStore() can also accept a function to calculate the initial value
  const state = useStore(() => {
    return {
      value: expensiveInitialValue(),
    };
  });
 
  return (
    <div>
      <div>Counter: {counter.value}</div>
      <Child userData={userData} state={state} />
    </div>
  );
});
 
function useCounter(step: number) {
  // Multiple stores can be created in custom hooks for convenience and composability
  const counterStore = useStore({
    value: 0,
  });
  useVisibleTask$(() => {
    // Only runs in the client
    const timer = setInterval(() => {
      counterStore.value += step;
    }, 500);
    return () => {
      clearInterval(timer);
    };
  });
  return counterStore;
}
useStore: <STATE extends object>(
  initialState: STATE | (() => STATE),
  opts?: UseStoreOptions,
) => STATE;

Parameter

Type

Description

initialState

STATE | (() => STATE)

opts

UseStoreOptions

(Optional)

STATE

Edit this section

UseStoreOptions

export interface UseStoreOptions

Property

Modifiers

Type

Description

deep?

boolean

(Optional) If true then all nested objects and arrays will be tracked as well. Default is true.

reactive?

boolean

(Optional) If false then the object will not be tracked for changes. Default is true.

Edit this section

useStyles$

A lazy-loadable reference to a component's styles.

Component styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)

import styles from "./code-block.css?inline";
 
export const CmpStyles = component$(() => {
  useStyles$(styles);
 
  return <div>Some text</div>;
});
useStyles$: (qrl: string) => UseStyles;

Parameter

Type

Description

qrl

string

UseStyles

Edit this section

UseStylesScoped

export interface UseStylesScoped

Property

Modifiers

Type

Description

scopeId

string

Edit this section

useStylesScoped$

A lazy-loadable reference to a component's styles, that is scoped to the component.

Component styles allow Qwik to lazy load the style information for the component only when needed. (And avoid double loading it in case of SSR hydration.)

import scoped from "./code-block.css?inline";
 
export const CmpScopedStyles = component$(() => {
  useStylesScoped$(scoped);
 
  return <div>Some text</div>;
});
useStylesScoped$: (qrl: string) => UseStylesScoped;

Parameter

Type

Description

qrl

string

UseStylesScoped

Edit this section

useTask$

Reruns the taskFn when the observed inputs change.

Use useTask to observe changes on a set of inputs, and then re-execute the taskFn when those inputs change.

The taskFn only executes if the observed inputs change. To observe the inputs, use the obs function to wrap property reads. This creates subscriptions that will trigger the taskFn to rerun.

useTask$: (qrl: import("./use-task").TaskFn, opts?: import("./use-task").UseTaskOptions | undefined) => void

Parameter

Type

Description

qrl

import("./use-task").TaskFn

opts

import("./use-task").UseTaskOptions | undefined

(Optional)

void

Edit this section

UseTaskOptions

export interface UseTaskOptions

Property

Modifiers

Type

Description

eagerness?

EagernessOptions

(Optional) - visible: run the effect when the element is visible. - load: eagerly run the effect when the application resumes.

Edit this section

useVisibleTask$

const Timer = component$(() => {
  const store = useStore({
    count: 0,
  });
 
  useVisibleTask$(() => {
    // Only runs in the client
    const timer = setInterval(() => {
      store.count++;
    }, 500);
    return () => {
      clearInterval(timer);
    };
  });
 
  return <div>{store.count}</div>;
});
useVisibleTask$: (qrl: import("./use-task").TaskFn, opts?: import("./use-visible-task").OnVisibleTaskOptions | undefined) => void

Parameter

Type

Description

qrl

import("./use-task").TaskFn

opts

import("./use-visible-task").OnVisibleTaskOptions | undefined

(Optional)

void

Edit this section

ValueOrPromise

Type representing a value which is either resolve or a promise.

export type ValueOrPromise<T> = T | Promise<T>;

Edit this section

version

QWIK_VERSION

version: string;

Edit this section

VisibleTaskStrategy

export type VisibleTaskStrategy =
  | "intersection-observer"
  | "document-ready"
  | "document-idle";

Edit this section

withLocale

Override the getLocale with lang within the fn execution.

export declare function withLocale<T>(locale: string, fn: () => T): T;

Parameter

Type

Description

locale

string

fn

() => T

T

Edit this section