Async & APIIntermediateSSR-safehooks/async/useApi.ts

useApi

useFetch with optional base URL.

Import

TypeScript
import { useApi } from '@/hooks';

API

Signature

useApi<T>(path, { baseUrl?, ... })

When to use

Use useApi instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Client-side. Prefer RSC for first-paint server data.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useApi
Editor
function Profile({ id }: { id: string }) {
  const { data, loading } = useApi<{ name: string }>(`/users/${id}`, {
    baseUrl: process.env.NEXT_PUBLIC_API_URL,
  });
  return loading ? <p>…</p> : <p>{data?.name}</p>;
}
Preview

Implementation source

Full library source for useApi — copy into your project when you are not installing a package yet.

hooks/async/useApi.ts
import { useFetch, type UseFetchOptions, type UseFetchReturn } from './useFetch';

export interface UseApiOptions<T> extends UseFetchOptions<T> {
  /** Optional base URL prefix. Caller still controls the full path. */
  baseUrl?: string;
}

/**
 * Thin API helper over `useFetch` with optional base URL composition.
 */
export function useApi<T = unknown>(
  path: string | null | undefined,
  options: UseApiOptions<T> = {},
): UseFetchReturn<T> {
  const { baseUrl = '', ...rest } = options;
  const url =
    path == null || path === ''
      ? path
      : path.startsWith('http')
        ? path
        : `${baseUrl.replace(/\/$/, '')}${path.startsWith('/') ? path : `/${path}`}`;

  return useFetch<T>(url, rest);
}

Copy-paste example

useApi.example.tsx
'use client';

import { useApi } from '@/hooks';

export function Profile({ id }: { id: string }) {
  const { data, loading } = useApi<{ name: string }>(`/users/${id}`, {
    baseUrl: process.env.NEXT_PUBLIC_API_URL,
  });
  return loading ? <p>…</p> : <p>{data?.name}</p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Abort in-flight work when the URL changes. Prefer null URL / enabled:false to skip.
  • Source of truth: open hooks/async/useApi.ts for implementation details