useLazyFetch
Fetch only when you call refetch.
Import
TypeScript
import { useLazyFetch } from '@/hooks';API
Signature
useLazyFetch<T>(url, options?)
When to use
Use useLazyFetch 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 · useLazyFetchEditor
function LoadOnClick() { const { data, loading, refetch } = useLazyFetch<{ users: unknown[] }>('/api/users'); return ( <button onClick={() => void refetch()} disabled={loading}> {data ? 'Loaded' : 'Load users'} </button> ); }
Preview
Implementation source
Full library source for useLazyFetch — copy into your project when you are not installing a package yet.
hooks/async/useLazyFetch.ts
import { useFetch, type UseFetchOptions, type UseFetchReturn } from './useFetch';
/**
* Lazy fetch — does not run until `refetch` is called.
*/
export function useLazyFetch<T = unknown>(
url: string | null | undefined,
options: Omit<UseFetchOptions<T>, 'immediate'> = {},
): UseFetchReturn<T> {
return useFetch<T>(url, { ...options, immediate: false });
}
Copy-paste example
useLazyFetch.example.tsx
'use client';
import { useLazyFetch } from '@/hooks';
export function LoadOnClick() {
const { data, loading, refetch } = useLazyFetch<{ users: unknown[] }>('/api/users');
return (
<button onClick={() => void refetch()} disabled={loading}>
{data ? 'Loaded' : 'Load users'}
</button>
);
}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/useLazyFetch.tsfor implementation details