Loaders are useful for one-time loading of data from the server to the client and can only be used in routes in your app
directory.
Loaders run on the server, for now they run based on their render mode - during build-time for SSG routes, or on each request for SPA or SSR routes.
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 you can access private information from within the loader. The data returned from the loader will be passed to the client, and so should be clear of private information. To access the loader data on the client, you must use the useLoader
hook:
import { useLoader } from 'one'
export async function loader() {
return {
user: 'tamagui'
}
}
export default function HomePage() {
const data = useLoader(loader)
return (
<p>
{data.user}
</p>
)
}
The useLoader hook is automatically type safe.
Loaders receive a single argument object:
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}`
}
}
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"
}
Only for ssr
type routes. This will pass the same Web standard Request object as API routes.
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',
},
})
}
A final 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
}
You can combine this with the redirect utility function:
import { redirect } from 'one'
export async function loader({ params: { id } }) {
const user = await db.users.findOne({ id })
if (!user) {
throw redirect('/login')
}
// ... rest of function
}
Edit this page on GitHub.