Resources

Read a value that only the browser can load, with use() under a <Suspense>. Each key loads once, and never on the server.

On this page

Defining

src/lib/highlighted.ts
import { defineResource } from '@k8ordo/effects';

export type Source = { code: string; lang: string };

export const highlighted = defineResource({
  load: async ({ code, lang }: Source) => {
    const query = new URLSearchParams({ code, lang });
    const response = await fetch(`/api/highlight?${query}`);
    return (await response.json()) as HighlightedCode;
  },
});

defineResource({ load }) defines a value that loads in the browser.

defineResource is not a hook, so it goes in a module without 'use client', and a Server Component’s module can import the same definition.

Reading

src/components/code.tsx
'use client';

import { useResource } from '@k8ordo/effects';
import { Suspense, useDeferredValue } from 'react';

import { highlighted } from '../lib/highlighted';
import type { Source } from '../lib/highlighted';

function Highlighted({ code, lang }: Source) {
  const tokens = useResource(highlighted, { code, lang });
Suspends until the value arrives
  return <Tokens tokens={tokens} />;
}

export function Code({ code, lang }: Source) {
  const deferredCode = useDeferredValue(code);
Keeps the old value on screen while a new key loads
  return (
    <Suspense fallback={<Plain code={code} />}>
The server renders this fallback
      <Highlighted code={deferredCode} lang={lang} />
    </Suspense>
  );
}

useResource(resource, key) reads the value with use(), from a Client Component.

The component suspends until the value arrives, and a rejection goes to the nearest error boundary. It needs a <Suspense> above it.

Once per key

Each key loads once. Every component that reads it, in every render, gets the same promise.

That is what use() needs: a promise made during render is new every render and suspends forever.

A key is anything JSON can write, and two keys that write the same JSON read one entry. Entries are kept for the life of the page.

On the server

useResource asks for the browser with use(browser()). The server writes the nearest <Suspense> fallback into its HTML, and load runs in the browser alone.

That is also why a resource is safe to define in a module. On the server, one module-level cache would be shared by every request, and one visitor’s data would reach another’s page.

What load does

src/lib/subscription.ts
const subscription = defineResource({
  load: async (scope: string) => {
    const { serviceWorker } = navigator;
    const registration = await serviceWorker.getRegistration(scope);
    return (await registration?.pushManager.getSubscription()) ?? null;
  },
});

load runs during a render, so it only reads: a fetch of a GET route, or a browser API like the one above.

A Server Function is for changes. It updates the framework’s state the moment it is called, which during a render is an update of another component while rendering, and calls queue one at a time.

Data the server can read is better read there, with no resource: a Server Component passes the promise down, and a Client Component reads it with use().

A new key

When the key comes from useDeferredValue, as in the first example, or changes inside startTransition, the old value stays on screen while the new key loads.

Otherwise the fallback shows meanwhile.

refresh

notification-toggle.tsx
const [isPending, startTransition] = useTransition();

<button
  disabled={isPending}
  onClick={() => {
    startTransition(async () => {
      await unsubscribe();
      startTransition(() => {
Wrapped in `startTransition` again after the `await`
        subscription.refresh(registrationScope);
      });
    });
  }}
  type="button"
>
  Turn off notifications
</button>;

resource.refresh(key) loads a key again, and every component reading it renders the new value. Call it after a change you know of.

Inside startTransition, the current value stays on screen until the new one arrives; outside it, the fallback shows meanwhile.

React does not carry a transition across an await yet, so wrap the call in startTransition again after it.

A key nobody reads yet starts loading, so refresh also loads ahead.

Warning

Pitfall

A rejected load stays rejected for its key, so every reader shows the error boundary’s fallback. To retry, call refresh(key) and reset the boundary.

k8ordo

React libraries that use Baseline features without holding back.