Components

Async setup

An async component awaits its data at the top of its setup, and the server renders what it loaded on every framework, then hydrates it in place.

Async setup lets a component load what it shows before it renders, like a profile that fetches its user, a team page that fetches its members or a label that fetches its translation. In Unframework you make the component async and await at the top of its setup, and every framework renders the loaded data, on the server too. Think of a profile that flashes an empty card before its data arrives, a server page that ships a spinner instead of the user's name, or a hydrated page that throws the server's HTML away and loads it all again.

This page walks you through writing one. We'll look at:

  • An async component: what you write, and what each framework does with it.
  • Async children: a parent that renders them, and a ref to one.
  • What the compiler checks: where an await may go, and what it may read.
  • What your app does: the one thing a Vue or a Svelte host adds.
  • What isn't guaranteed: what differs between frameworks.

An async component

Make the component async, and declare each value it waits for as a const at the top of its setup. What comes after the awaits reads the loaded values as plain constants, so state can start from them:

Profile.uf.tsx
import { ref } from "@uxfront/unframework";

import { loadUser } from "./api";

// A setup that awaits a user, then keeps a count that starts from what it loaded.
export default async function Profile({ id }: { id: string }) {
  const user = await loadUser(id);
  const visits = ref(user.visits);

  return (
    <p class="profile">
      {user.name}{" "}
      <button type="button" onClick={() => visits.value++}>
        Visits: {visits.value}
      </button>
    </p>
  );
}

loadUser comes from a shared module, which every output imports as it is:

api.ts
// The loaders the async-setup cases await (ADR-0101): deterministic, so the server and the
// client resolve to the same values, and each resolves after one microtask, before the harness
// settles a mount.
export interface User {
  name: string;
  visits: number;
  teamId: string;
}

export async function loadUser(id: string): Promise<User> {
  await Promise.resolve();
  return { name: `User ${id}`, visits: id.length, teamId: `team-${id.length}` };
}

export async function loadTeam(id: string): Promise<{ name: string }> {
  await Promise.resolve();
  return { name: `Team ${id}` };
}

The server waits for the setup and renders the loaded data, with no fallback and no wrapper element. A component mounted in the browser renders nothing until its setup resolves, then renders. After a server render hydrates, the setup runs again in the browser while the server's HTML stays as it is, and the button responds once the setup has resolved. So load the same data on both sides: a value that differs updates the page, and Vue and React report a hydration mismatch for it.

The awaited call reads its props once, when the setup runs. A later prop changes what the template reads, not what the setup loaded.

Vue and Svelte await in place, under Vue's <Suspense> and in Svelte's async mode. React runs the awaits in a function of the module and reads the result with use, Solid in a resource whose result a <Show> renders, Angular in ngOnInit while a pending task holds the render, and Qwik through an async useComputed$. Astro awaits in its frontmatter:

Profile.tsx
import { loadUser } from "./api";
import { type CSSProperties, Suspense, use, useEffect, useRef, useState } from "react";

export interface ProfileAttributes {
  className?: string;
  style?: CSSProperties;
}

async function profileSetup({ id }: { id: string }) {
  const user = await loadUser(id);
  return { user };
}

export default function Profile(props: { id: string } & ProfileAttributes) {
  const [setup] = useState(() => profileSetup(props));
  const [settled, setSettled] = useState(false);

  return (
    <Suspense fallback={<SetupPending setup={setup} onSettled={setSettled} />}>
      <ProfileResolved {...props} setup={setup} settled={settled} />
    </Suspense>
  );
}

function ProfileResolved({
  className,
  style,
  setup,
  settled: _settled,
  ...attributes
}: { id: string } & ProfileAttributes & {
    setup: ReturnType<typeof profileSetup>;
    settled: boolean;
  }) {
  const { user } = use(setup);

  const [visits, setVisits] = useState(user.visits);
  const visitsRef = useRef(visits);

  return (
    <p className={cx("profile", className)} style={style} {...scopeAttributes(attributes)}>
      {user.name}{" "}
      <button
        type="button"
        onClick={() => {
          visitsRef.current++;
          setVisits(visitsRef.current);
        }}
      >
        Visits: {visits}
      </button>
    </p>
  );
}

/** Joins class names, and the keys of an object's truthy entries, into one `className`. */
function cx(...parts: unknown[]): string {
  const names: string[] = [];
  for (const part of parts) {
    if (typeof part === "string") {
      if (part) names.push(part);
    } else if (part && typeof part === "object") {
      for (const [key, on] of Object.entries(part)) {
        if (on) names.push(key);
      }
    }
  }
  return names.join(" ");
}

/** The scope attributes of the styled parents that render this component, for its root. */
function scopeAttributes(props: object): Record<string, ""> {
  const scope: Record<string, ""> = {};
  for (const key of Object.keys(props)) {
    if (key.startsWith("data-uf-")) scope[key] = "";
  }
  return scope;
}

/**
 * Renders nothing while a setup runs, and tells the component once it settles, so React shows the
 * content at once rather than after its fallback throttle. Only a fallback React commits runs it:
 * never on the server, and never while the client hydrates.
 */
function SetupPending({
  setup,
  onSettled,
}: {
  setup: Promise<unknown>;
  onSettled: (settled: boolean) => void;
}): null {
  useEffect(() => {
    let live = true;
    const settle = () => {
      if (live) onSettled(true);
    };
    setup.then(settle, settle);
    return () => {
      live = false;
    };
  }, [setup, onSettled]);
  return null;
}

Async children

A parent renders an async child like any other, whether the parent is async or not. Each child loads on its own, and a ref to one reaches its exposed functions once its setup has resolved:

Team.uf.tsx
import { useTemplateRef } from "@uxfront/unframework";

import Lead from "./Lead.uf.tsx";
import Member from "./Member.uf.tsx";

// A sync parent around async children: one it holds a ref to, a list of them, and one through a
// component whose root is an async child.
export default function Team({ ids }: { ids: string[] }) {
  const first = useTemplateRef<{ reset(): void }>();

  return (
    <section class="team" aria-label="Team">
      <h2>Team</h2>
      <button type="button" onClick={() => first.value?.reset()}>
        Reset
      </button>
      <Member ref={first} id="ada" />
      <ul>
        {ids.map((id) => (
          <li key={id}>
            <Member id={id} />
          </li>
        ))}
      </ul>
      <Lead class="lead" id="hopper" />
    </section>
  );
}

Vue renders an async setup only under a <Suspense>, so the parent's Vue output wraps each async child in one. It reads that the child is async from the child's own module:

Team.vue
<script setup lang="ts">
import Lead from "./Lead.vue";
import Member from "./Member.vue";
import { useTemplateRef } from "vue";

const { ids } = defineProps<{ ids: string[] }>();

const first = useTemplateRef<{ reset(): void }>("first");
</script>

<template>
  <section class="team" aria-label="Team">
    <h2>Team</h2>
    <button type="button" @click="first?.reset()">Reset</button>
    <Suspense>
      <Member id="ada" ref="first" />
    </Suspense>
    <ul>
      <li v-for="id in ids" :key="id">
        <Suspense>
          <Member :id="id" />
        </Suspense>
      </li>
    </ul>
    <Lead id="hopper" class="lead" />
  </section>
</template>

Lead renders nothing but a Member, so the class that Team passes to Lead reaches the Member's root, as with any child at a component's root.

What the compiler checks

An await at the top of the setup is the whole value of a const that declares one name. One inside a larger expression, a destructuring, a let, a bare statement or a condition is rejected, UF2038, since not every framework has a form for it:

Profile.uf.tsx
// UF2038 nested-await: an async setup awaits only as the whole value of a top-level `const` that
// declares one name, so a destructured await, an await inside a larger expression, a bare await
// and an await inside an `if` are rejected.
import { loadUser } from "./api";

export default async function Profile({ id }: { id: string }) {
  const { name } = await loadUser(id);
  const visits = (await loadUser(id)).visits;
  await loadUser(id);
  if (id) {
    await loadUser(id);
  }
  return (
    <p>
      {name} {visits}
    </p>
  );
}

The awaits come before the setup's other items, and an awaited expression reads only props, the module's values, globals and the values awaited before it, UF2039. React and Solid run the awaits apart from the component, where nothing else of the setup exists yet:

Profile.uf.tsx
// UF2039 late-await: the awaits open the setup and read only props, module values, globals and
// earlier awaits, so an await after a ref and an awaited expression that reads `emit` are
// rejected.
import { defineEmits, ref } from "@uxfront/unframework";

import { loadUser } from "./api";

export default async function Profile({ id }: { id: string }) {
  const emit = defineEmits<{ load: [id: string] }>();
  const user = await loadUser(String(emit));
  const count = ref(0);
  const team = await loadUser(id);
  return (
    <p>
      {user.name} {team.name} {count.value}
    </p>
  );
}

An await inside a function the setup declares, like a handler, is client code, and stays allowed. An async component as a candidate of <component is> isn't supported yet, and neither is an async composable.

What your app does

A component in a .uf.tsx file needs nothing more. Two frameworks ask one thing of an app that renders the outputs itself:

  • Vue. A hand-written Vue parent wraps an async component in <Suspense>, which Vue requires for any async setup. Without it, Vue warns and never renders the component.
  • Svelte. The app sets compilerOptions.experimental.async for each file whose script awaits, or for the whole app. Without it, Svelte reports its own experimental_async error at the await. Svelte labels the option experimental, and once one async component loads, Svelte's async mode is on for the whole page.

On Svelte, a provide after the awaits moves above them, since Svelte allows it only while a component starts. One whose key or value reads an awaited value can't move, so the compiler rejects it on Svelte, UF1002.

What isn't guaranteed

The setup runs again in the browser after a server render hydrates, so don't depend on it running once across the server and the browser, nor on it running twice: Qwik resumes the page without running it again. A few things differ between frameworks:

  • Solid creates the hydrated component's elements again once the setup resolves, so focus and selection inside them reset.
  • On React, a prop that changes while the component hydrates and its setup still runs makes React render it in the browser, without the server's HTML until the setup resolves.
  • A setup whose promise rejects throws its own way on each framework, and nothing catches it yet.
  • Whether a parent's markup waits for an async child as it mounts in the browser. Svelte's does, and the others render it at once.

The decision behind this page is ADR-0101. The rule is on the semantics page.

Copyright © 2026