One Logo Pool Ball
wwwwwwwwwwwwwwwwwww

Loaders

Loaders are useful for one-time loading of data from the server to the client. They can be used in both page routes and layout files in your app directory.

Loaders run on the server based on their render mode - during build-time for SSG routes, or on each request for SPA or SSR routes. Layout loaders and page loaders run in parallel for optimal performance.

Native Platform Behavior

Loaders work similarly on native platforms as they do on web:

This means native apps can use the same loader patterns as web apps, with data fetching behavior determined by the route’s render mode rather than the platform.

Loaders and their imports are removed from client bundles, so server-only loader code can access private information. The data returned from a loader is sent to the client. Never return secrets or other information that should stay on the server.

Accessing Loader Data

There are two hooks available for accessing loader data:

useLoader

The basic hook for accessing loader data:

import { useLoader } from 'one'
export async function loader() {
return {
user: 'tamagui'
}
}
export default function HomePage() {
const data = useLoader(loader)
return (
<p>
{data.user}
</p>
)
}

useLoaderState

For advanced use cases requiring manual refetch or loading states:

import { useLoaderState } from 'one'
export async function loader() {
return {
user: 'tamagui'
}
}
export default function HomePage() {
const { data, refetch, state } = useLoaderState(loader)
return (
<>
<p>{data.user}</p>
<button onClick={refetch} disabled={state === 'loading'}>
Refresh
</button>
</>
)
}

Both hooks are automatically type safe. See useLoader and useLoaderState for detailed documentation.

refetchLoader

Re-run the loader for a path imperatively, outside of React. This is useful in event handlers or background tasks where hooks are not available:

import { refetchLoader } from 'one'
async function refreshUser(id: string) {
await refetchLoader(`/users/${id}`)
}

The promise resolves when the refetch completes. Components reading that loader through useLoader or useLoaderState re-render with the fresh data.

onClientLoaderResolve

Runs once on the client after hydration preloads finish and before the first render. Register it in your root _layout.tsx when you need to observe the initial loader payload from outside React:

import { onClientLoaderResolve } from 'one'
onClientLoaderResolve(({ loaderData, loaderProps }) => {
console.log('hydrated loader data for', loaderProps?.path, loaderData)
})

It must be registered before the client finishes setup, so call it at the top level of your root layout module. Calling it after it already ran throws.

useMatches

To access loader data from other routes (like a layout accessing page data, or vice versa), use useMatches:

import { useMatches } from 'one'
function Breadcrumbs() {
const matches = useMatches()
// matches = [rootLayout, nestedLayout, currentPage]
// each has: { routeId, pathname, params, loaderData }
// loaderData is unknown, so narrow it before reading fields
return (
<nav>
{matches.map(match => {
const { title } = (match.loaderData ?? {}) as { title?: string }
return (
<a key={match.routeId} href={match.pathname}>
{title ?? match.routeId}
</a>
)
})}
</nav>
)
}

See useMatches for detailed documentation.

Layout Loaders

Layouts can export a loader function just like pages:

app/docs/_layout.tsx
import { useLoader, Slot } from 'one'
export async function loader() {
return {
navItems: await fetchDocsNav()
}
}
export default function DocsLayout() {
const { navItems } = useLoader(loader)
return (
<div>
<Sidebar items={navItems} />
<Slot />
</div>
)
}

See Layout Loaders for more details.

Loader arguments

Loaders receive a single argument object:

params

The params key will provide values from any dynamic route segments:

app/user/[id].tsx
export async function loader({ params }) {
// for route /user/jamon params.id is a string "jamon"
const user = await getUser(params.id)
return {
greet: `Hello ${user.name}`
}
}

path

The path key is the fully resolved pathname:

app/user/[id].tsx
export async function loader({ path }) {
// if the route is /user/123 then path is "/user/123"
}

request

Only for ssr type routes. This will pass the same Web standard Request object as API routes.

searchParams

Only for ssr type routes. When components under the route pass a schema to useSearchParams(schema), the server validates the query before the loader runs and passes the result as searchParams. An invalid query answers 400 and the loader does not run; a client navigation to it loads the URL as a document so the 400 shows. Client navigation and refetchLoader send the page’s query too, so the loader receives the same searchParams and its data is stored per query.

Accepted Return Types

Most JavaScript values, including primitives and objects, will be converted to JSON.

You may also return a Response:

export async function loader({ params: { id } }) {
const user = await db.users.findOne({ id })
const body = JSON.stringify(user)
return new Response(body, {
headers: {
'Content-Type': 'application/json',
},
})
}

Returning JSX from a Loader

A loader can return rendered JSX along with its data. Call renderJSX with a React tree on the server. It walks the tree, runs your server components, and returns a compact JSON envelope. useLoader and useMatches turn the envelope back into elements for you, typed as React.ReactNode, so the page renders it like any other child:

app/feed+ssr.tsx
import { renderJSX, useLoader } from 'one'
import { Text, YStack } from 'tamagui'
import { Counter } from '../components/Counter'
import { getPost, getPosts } from '../server/posts'
async function PostCard({ id }: { id: string }) {
const post = await getPost(id)
return <Text>{post.title}</Text>
}
export async function loader() {
const posts = await getPosts()
return {
ui: await renderJSX(
<YStack>
{posts.map((post) => (
<PostCard key={post.id} id={post.id} />
))}
<Counter label="likes" start={0} />
</YStack>
),
}
}
export default function FeedPage() {
const { ui } = useLoader(loader)
return <>{ui}</>
}

Server functions like PostCard run on the server when the loader runs. Siblings resolve in parallel and stay in tree order even when they finish out of order. Because they only run inside the loader, they can use server-only imports, and none of that code ships in the client or native bundle. Keys are preserved, so when a refetch reorders a list, island state follows the item it belongs to.

This boundary is explicit. The production client bundle receives the JSON envelope, the small revival runtime, the 'use client' islands the server graph references, and the universal components it references. It does not receive renderJSX, server components, or imports reachable only from the loader. Host-only and server-component subtrees therefore add no component JavaScript of their own. The page and router still hydrate as usual, and values returned from the loader still cross to the client, so keep secrets in loader-only imports or .server.ts modules rather than in props or rendered output.

Client islands

A component from a file that starts with 'use client' stays a reference in the envelope and renders on the client, interactive after hydration:

components/Counter.tsx
'use client'
import { useState } from 'react'
import { Button, Text } from 'tamagui'
export function Counter({ label, start }: { label: string; start: number }) {
const [count, setCount] = useState(start)
return (
<Button onPress={() => setCount((c) => c + 1)}>
<Text>
{label}: {count}
</Text>
</Button>
)
}

Props you pass to a client island cross to the client as JSON. Plain data (strings, numbers, booleans, arrays and objects of those) and React elements are allowed, including elements nested inside prop objects. An array that contains elements arrives as a single fragment node rather than an array. Functions, Date objects, class instances, bigints, symbols and non-finite numbers are rejected with an error that names the offending prop. Event handlers belong inside the island, not in props passed from the server tree.

You can also reference some universal components directly in a server tree, with no 'use client' file: Link from one, and the Tamagui primitives View, Text, Stack, XStack, YStack, ZStack, Paragraph, SizableText, H1 to H6, Image, Spacer and Separator. Prefer these over host elements like div in trees that also render on native, where host element names do not exist.

Version skew

A native app (or a stale web client) may not know an island a newer server sends. Wrap the island in ClientFallback to choose what shows instead:

import { ClientFallback } from 'one'
<ClientFallback fallback={<Text>Update the app to see this</Text>}>
<NewChart data={data} />
</ClientFallback>

An unknown island renders the fallback, in place, once the client hydrates. Without a ClientFallback, an unknown island renders nothing.

Slots

JSXSlot leaves a named hole in a server tree that the client fills in, rendering its children until then:

import { JSXSlot } from 'one'
<JSXSlot name="footer" tone="dim">
<Text>Loading footer...</Text>
</JSXSlot>

Slot filling happens when you revive an envelope yourself with ServerJSX (or reviveLoaderJSX), for example an envelope your own API returned:

import { ServerJSX } from 'one'
<ServerJSX value={envelope} slots={{ footer: (props) => <Footer tone={props.tone} /> }} />

Route loaders revive automatically without slots, so a slot in loader JSX renders its fallback children there.

Rules for server trees

Loader JSX is one-way. The tree is computed when the loader runs, and a refetch replaces it with a new one. There is no streaming protocol and no server actions: anything interactive lives in a client island, and anything the island needs from the server arrives as props or through your own API routes.

Throwing a Response

A handy pattern for loaders is throwing a response to end it early:

export async function loader({ params: { id } }) {
const user = await db.users.findOne({ id })
if (!user) {
throw Response.error()
}
// ... rest of function
}

Redirects in Loaders

Use the redirect() helper in loaders to protect SSR routes. This is the recommended approach for server-side auth guards — it prevents unauthorized content from ever reaching the client.

app/dashboard+ssr.tsx
import { redirect, useLoader } from 'one'
import type { LoaderProps } from 'one'
export async function loader({ request }: LoaderProps) {
const session = await getSession(request)
if (!session) {
throw redirect('/login')
}
return { user: session.user }
}
export default function Dashboard() {
const { user } = useLoader(loader)
return <Text>Welcome, {user.name}</Text>
}

Both throw redirect() and return redirect() work. throw is often cleaner since it stops execution immediately and makes it obvious the remaining code won’t run.

How Loader Redirects Work

During a direct page load, redirect() returns a standard HTTP 302 response — the browser redirects normally.

During client-side <Link> navigation, loaders run on the server and the client fetches the result as a JavaScript module. Without special handling, the browser’s module loader would silently follow a 302, try to parse the HTML login page as JavaScript, and fail. One handles this differently:

  1. The server detects the redirect response from the loader
  2. Instead of returning a raw 302, it transforms the response into a JS module containing redirect metadata
  3. The client receives the metadata and detects the redirect signal before rendering anything
  4. The client navigates to the redirect target using a REPLACE action — the protected page never appears in the history

This means no sensitive data reaches the client when a redirect occurs. The server only sends back the redirect path, not the page content or loader data.

Redirects at Build Time

For SSG routes, if a loader redirects during the build (e.g., no authenticated request is available), One generates a static redirect file. In production with a runtime server, the server re-evaluates the loader on each request, so authenticated users see the real page while unauthenticated users get redirected.

Use +ssr routes for protected pages so loaders run on every request. SSG routes evaluate loaders once at build time, which won’t have access to per-request auth state.

See the Loader Redirects guide for a complete walkthrough and the redirect helper for the API reference.

Setting Response Headers

Use setResponseHeaders to set HTTP headers on the response from within your loader. This is useful for caching, cookies, and custom headers.

Cache Headers (ISR)

Set cache headers to enable Incremental Static Regeneration - serve SSR pages with static-like performance:

import { setResponseHeaders, useLoader } from 'one'
export async function loader({ params }) {
// Cache at CDN for 1 hour, serve stale while revalidating for up to 1 day
await setResponseHeaders((headers) => {
headers.set('Cache-Control', 'public, s-maxage=3600, stale-while-revalidate=86400')
})
const post = await fetchPost(params.slug)
return { post }
}

Cookies

Set cookies by appending Set-Cookie headers:

import { setResponseHeaders } from 'one'
export async function loader({ params }) {
await setResponseHeaders((headers) => {
headers.append('Set-Cookie', `visited=${params.slug}; Path=/; HttpOnly`)
})
return { /* ... */ }
}

Read cookies from the request (SSR routes only):

export async function loader({ request }) {
const cookies = request?.headers.get('Cookie') || ''
const session = cookies.match(/session=([^;]+)/)?.[1]
if (!session) {
throw redirect('/login')
}
return { user: await getUser(session) }
}

Custom Headers

Add any custom headers:

await setResponseHeaders((headers) => {
headers.set('X-Custom-Header', 'value')
headers.set('X-Request-Id', crypto.randomUUID())
})

See setResponseHeaders for more details.

Loader Cache

Routes can export a loaderCache function to deduplicate concurrent SSR loader calls. When multiple requests hit the same route at the same time, only one loader execution runs and the result is shared across all waiting requests.

Basic usage

Return a string key from loaderCache to coalesce concurrent requests with matching keys:

app/cards/[id]+ssr.tsx
import { useLoader } from 'one'
import { db } from '~/lib/db'
// concurrent requests with the same id share one loader call
export const loaderCache = (params: { id: string }) => params.id
export async function loader({ params }) {
const card = await db.getCardWithListings(params.id)
return { card }
}
export default function CardPage() {
const { card } = useLoader(loader)
return <CardDetail card={card} />
}

Without ttl, only truly concurrent requests are coalesced — the cache entry is cleaned up immediately after the loader resolves.

TTL-based caching

Return an object with key and ttl to cache the result for a time window (in milliseconds):

export const loaderCache = (params: { id: string }) => ({
key: params.id,
ttl: 100, // cache for 100ms
})

With ttl, subsequent requests within the TTL window reuse the cached result without running the loader again.

Auth-aware cache keys

loaderCache receives (params, request) so you can include auth headers or other request data in the key:

export const loaderCache = (params, request) => {
const userId = request?.headers.get('x-user-id') || 'anon'
return `${params.id}:${userId}`
}

When to use loaderCache

Hot Reload for File Dependencies

During development, you can use watchFile to register file dependencies in your loader. When these files change, the loader data will automatically refresh without a full page reload.

This is useful for content-driven sites where loaders read from MDX files, JSON, or other data files:

import { watchFile } from 'one'
import { readFile } from 'fs/promises'
export async function loader({ params: { slug } }) {
const filePath = `./content/${slug}.mdx`
// Register this file for HMR - when it changes, loader will re-run
watchFile(filePath)
const content = await readFile(filePath, 'utf-8')
return { content }
}

watchFile is a no-op in production and on the client, so it’s safe to use unconditionally. The path should be the same path you pass to fs.readFile or similar functions.

Using @vxrn/mdx

The @vxrn/mdx package has built-in HMR support. When used in a One loader, MDX files will automatically trigger hot reload when changed:

import { getMDXBySlug } from '@vxrn/mdx'
export async function loader({ params: { slug } }) {
// HMR is automatic - no watchFile needed
const { frontmatter, code } = await getMDXBySlug('./content', slug)
return { frontmatter, code }
}

For Library Authors

If you’re building a library that reads files and want to support One’s loader HMR, you can use the global hook pattern. This allows your library to work with One’s HMR without depending on the one package:

const WATCH_FILE_KEY = '__oneWatchFile'
function notifyFileRead(filePath: string): void {
const watchFile = globalThis[WATCH_FILE_KEY] as ((path: string) => void) | undefined
if (watchFile) {
watchFile(filePath)
}
}
// Call this whenever you read a file
export function readContent(filePath: string) {
notifyFileRead(filePath)
return fs.readFileSync(filePath, 'utf-8')
}

When One is present, it registers the watchFile implementation on the global object. Your library checks for it and calls it if available - no coupling required. The @vxrn/mdx package exports notifyFileRead if you prefer to import it directly.

Route Validation

One provides two ways to validate routes before navigation: validateParams for schema-based validation and validateRoute for async validation logic.

validateParams

Export a schema to validate route params before navigation. Works with Zod, Valibot, or custom functions:

import { z } from 'zod'
// Validate that id is a UUID
export const validateParams = z.object({
id: z.string().uuid('Invalid ID format')
})
export default function UserPage({ params }) {
// params.id is guaranteed to be a valid UUID
return <UserDetail userId={params.id} />
}

If validation fails, validateParams throws a ParamValidationError (with params and issues fields), navigation is blocked and an error is shown in the Error Panel (Alt+E).

For Zod schemas, wrap with zodParamValidator so the validator keeps its inferred output type:

import { zodParamValidator } from 'one'
import { z } from 'zod'
export const validateParams = zodParamValidator(z.object({
id: z.string().uuid('Invalid ID format'),
}))

The related types are exported from one: ParamValidator, InferParamInput, InferParamOutput, and ParamValidationError.

validateRoute

For async validation (like checking if a resource exists), export a validateRoute function:

export async function validateRoute({ params, search, pathname }) {
// Check if the product exists before allowing navigation
const exists = await checkProductExists(params.slug)
if (!exists) {
return {
valid: false,
error: 'Product not found',
details: { slug: params.slug }
}
}
return { valid: true }
}
export default function ProductPage({ params }) {
// We only get here if the product exists
return <ProductDetail slug={params.slug} />
}

The function receives { params, search, pathname, href } (see ValidateRouteProps) and must return { valid: true } or { valid: false, error, details? } (see ValidationResult). It can also return nothing, which counts as valid. The related handler type is RouteValidationFn.

validateParams vs validateRoute

Both can validate routes, but they serve different purposes:

FeaturevalidateParamsvalidateRoute
Runs onClientClient
Use caseSchema validationAsync checks

Use validateParams for simple schema validation (UUIDs, formats, types).

Use validateRoute for async checks on the client (API calls, existence checks).

For server-side auth and redirects, use your loader function and throw a redirect response.

useValidationState

Access validation state from any component:

import { useValidationState } from 'one'
function NavigationStatus() {
const { status, error } = useValidationState()
// status: 'idle' | 'validating' | 'error' | 'valid'
// error is set only when status is 'error'
if (status === 'validating') {
return <Spinner />
}
if (status === 'error') {
return <Alert>{error?.message}</Alert>
}
return null
}

The state also carries lastValidatedHref, the href that was last validated. The error is a ParamValidationError when validateParams fails, or a RouteValidationError (with a details field) when validateRoute returns { valid: false }.

Edit this page on GitHub.