Docs
Advanced Usage
Preloading

Preloading

You can reduce the time taken for initial rendering by preloading data before navigating to an activity. Stackflow's built-in Loader API makes this straightforward.

Loader API

Define a loader for your activity in stackflow.config.ts. The loader runs before the activity renders and its data is accessible via useLoaderData().

HomeActivity.loader.ts
import type { ActivityLoaderArgs } from "@stackflow/react";
 
export async function homeActivityLoader({ params }: ActivityLoaderArgs<"HomeActivity">) {
  const data = await fetchData(params);
  return { data };
}
stackflow.config.ts
import { defineConfig } from "@stackflow/config";
import { homeActivityLoader } from "./HomeActivity.loader";
 
export const config = defineConfig({
  activities: [
    {
      name: "HomeActivity",
      route: "/",
      loader: homeActivityLoader,
    },
  ],
  transitionDuration: 350,
});

Access the loader data inside the activity component:

HomeActivity.tsx
import { useLoaderData, type ActivityComponentType } from "@stackflow/react";
import type { homeActivityLoader } from "./HomeActivity.loader";
 
const HomeActivity: ActivityComponentType<"HomeActivity"> = () => {
  const loaderData = useLoaderData<typeof homeActivityLoader>();
 
  return (
    <div>{/* use loaderData */}</div>
  );
};

API Pipelining

For advanced use cases, you can further reduce loading time by initiating API requests in parallel with React app initialization. See the API Pipelining guide for details.