| name | qwik |
| description | [Applies to: **/*.{js,jsx,ts,tsx}] This guide outlines definitive best practices for building high-performance, resumable Qwik applications, focusing on maximizing lazy loading and ensuring optimal developer experience. |
| source | cursor_mdc |
qwik Best Practices
Qwik is an edge-first framework built on resumability, not hydration. This means your application's JavaScript is only loaded and executed when absolutely necessary, leading to instant Time-To-Interactive (TTI). Our guidelines prioritize this core principle.
Critical Guidelines:
1. Define Every UI Piece with component$
All interactive UI components must be wrapped in component$. This is Qwik's fundamental primitive for enabling automatic code-splitting and lazy loading.
❌ BAD: Regular function component
export const MyButton = () => {
return <button onClick={() => alert('Clicked!')}>Click me</button>;
};
✅ GOOD: component$ for resumability
import { component$ } from '@builder.io/qwik';
export const MyButton = component$(() => {
return <button onClick$={() => alert('Clicked!')}>Click me</button>;
});
2. Use useStore for Reactive State
Manage component-local reactive state using useStore. This ensures state is serializable and resumable across server-side rendering and client-side interactions. Always type your stores for clarity and safety.
❌ BAD: Non-reactive or non-serializable state
import { component$ } from '@builder.io/qwik';
export const Counter = component$(() => {
let count = 0;
const increment = () => { count++; };
return <button onClick$={increment}>{count}</button>;
});
✅ GOOD: useStore with TypeScript interface
import { component$, useStore } from '@builder.io/qwik';
interface CounterStore {
count: number;
}
export const Counter = component$(() => {
const store = useStore<CounterStore>({ count: 0 });
return (
<button onClick$={() => store.count++}>
Count: {store.count}
</button>
);
});
3. Defer Client-Side Effects with useVisibleTask$
Execute client-specific logic, such as third-party library initialization or DOM manipulation, only when a component becomes visible in the viewport. This prevents unnecessary JavaScript execution on initial load. For effects that must run on the client regardless of visibility, use useClientEffect$.
❌ BAD: Eager client-side effect in component render
import { component$ } from '@builder.io/qwik';
import Chart from 'chart.js';
export const ChartComponent = component$(() => {
const canvasRef = useRef<HTMLCanvasElement>();
useEffect(() => {
if (canvasRef.current) {
new Chart(canvasRef.current, { });
}
}, []);
return <canvas ref={canvasRef}></canvas>;
});
✅ GOOD: useVisibleTask$ for client-side effects
import { component$, useSignal, useVisibleTask$ } from '@builder.io/qwik';
import type Chart from 'chart.js';
export const ChartComponent = component$(() => {
const canvasRef = useSignal<HTMLCanvasElement>();
useVisibleTask$(({ track }) => {
track(() => canvasRef.value);
if (canvasRef.value) {
import('chart.js').then(({ default: Chart }) => {
new Chart(canvasRef.value!, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow'],
datasets: [{
label: '# of Votes',
data: [, , ],
: [, , ],
}],
},
});
});
}
});
;
});
4. Use $ Suffix for All QRLs
Any function that needs to be code-split and lazy-loaded by Qwik's optimizer must end with a $ suffix. This includes components (component$), event handlers (onClick$, onInput$), and hooks (useStore, useTask$, useVisibleTask$, useClientEffect$, useResource$, useSignal$).
❌ BAD: Missing $ suffix on event handler
import { component$ } from '@builder.io/qwik';
export const MyButton = component$(() => {
const handleClick = () => {
console.log('Button clicked!');
};
return <button onClick={handleClick}>Click me</button>;
});
✅ GOOD: Correct $ suffix for QRLs
import { component$ } from '@builder.io/qwik';
export const MyButton = component$(() => {
const handleClick = component$(() => {
console.log('Button clicked!');
});
return <button onClick$={handleClick}>Click me</button>;
});
5. Leverage Qwik City for Routing and Data Loading
For applications using Qwik City, utilize its file-system based routing, layouts, and loader$ functions for efficient data fetching. This provides a zero-overhead solution for server-side data loading and routing.
❌ BAD: Manual routing or client-side data fetching for initial load
import { component$, useClientEffect$, useStore } from '@builder.io/qwik';
export default component$(() => {
const store = useStore({ products: [] });
useClientEffect$(async () => {
const res = await fetch('/api/products');
store.products = await res.json();
});
return <div>{/* ... render products ... */}</div>;
});
✅ GOOD: loader$ for server-side data fetching
import { component$ } from '@builder.io/qwik';
import { routeLoader$ } from '@builder.io/qwik-city';
interface Product {
id: string;
name: string;
}
export const useProducts = routeLoader$(async () => {
const res = await fetch('https://api.example.com/products');
const products: Product[] = await res.json();
return products;
});
export default component$(() => {
const products = useProducts();
return (
<div>
<h1>Products</h1>
<ul>
{products.value.map((product) => (
<li key={product.id}>{product.name}</li>
))}
);
});
6. Use PropFunction for Passing Functions as Props
When passing a function as a prop to a child component that itself is a component$, ensure the prop type is PropFunction<(...args: any[]) => any>. This signals to Qwik that the function is a QRL and should be serialized and lazy-loaded.
❌ BAD: Passing a regular function type as a prop
import { component$ } from '@builder.io/qwik';
interface ChildButtonProps {
onClick: () => void;
}
export const ChildButton = component$((props: ChildButtonProps) => {
return <button onClick$={props.onClick}>Child Button</button>;
});
import { component$ } from '@builder.io/qwik';
import { ChildButton } from './child-button';
export const ParentComponent = component$(() => {
const handleParentClick = component$(() => console.log('Parent handled click'));
return <ChildButton onClick={handleParentClick} />;
});
✅ GOOD: Using PropFunction for function props
import { component$, type PropFunction } from '@builder.io/qwik';
interface ChildButtonProps {
onClick$: PropFunction<() => void>;
}
export const ChildButton = component$((props: ChildButtonProps) => {
return <button onClick$={props.onClick$}>Child Button</button>;
});
import { component$ } from '@builder.io/qwik';
import { ChildButton } from './child-button';
export const ParentComponent = component$(() => {
const handleParentClick = component$(() => console.log('Parent handled click'));
return <ChildButton onClick$= />;
});
7. Adopt Atomic CSS (e.g., Tailwind CSS)
Integrate styling solutions like Tailwind CSS that generate static, utility-first classes at build time. This avoids runtime style calculations and keeps CSS payloads minimal, aligning with Qwik's performance goals.
❌ BAD: Runtime CSS-in-JS or complex dynamic styling
import { component$ } from '@builder.io/qwik';
import { css } from '@emotion/css';
const buttonStyle = css`
background-color: blue;
color: white;
padding: 10px 20px;
border-radius: 5px;
&:hover {
background-color: darkblue;
}
`;
export const StyledButton = component$(() => {
return <button class={buttonStyle}>Styled Button</button>;
});
✅ GOOD: Tailwind CSS for static styling
import { component$ } from '@builder.io/qwik';
export const TailwindButton = component$(() => {
return (
<button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
Tailwind Button
</button>
);
});
8. Use Vitest and Playwright for Testing
Leverage Qwik's built-in testing stack: Vitest for unit and component tests, and Playwright for end-to-end scenarios. These tools are integrated and optimized for Qwik's unique architecture, ensuring your lazy-loading and resumability work correctly.
❌ BAD: Using Jest/Enzyme for Qwik component testing
import { render } from '@testing-library/react';
import { MyComponent } from './my-component';
test('MyComponent renders correctly', () => {
const { getByText } = render(<MyComponent />);
expect(getByText('Hello')).toBeInTheDocument();
});
✅ GOOD: Vitest for Qwik component testing
import { render, screen } from '@builder.io/qwik/testing';
import { component$ } from '@builder.io/qwik';
import { MyComponent } from './my-component';
describe('MyComponent', () => {
it('should render correctly', async () => {
await render(<MyComponent />);
expect(screen.getByText('Hello Qwik!')).toBeInTheDocument();
});
it('should handle click event', async () => {
const mockFn = vi.fn();
const TestComponent = component$(() => {
return <button onClick$={mockFn}>Click Me</button>;
});
await render(<TestComponent />);
await screen.getByRole('button', { : }).();
(mockFn).();
});
});