Examples
Every example is a small, complete app you can run in the browser, open in StackBlitz or CodeSandbox, or copy to your machine. Each one focuses on a single idea and explains what it shows and how it works.
- Read the page to see what the example shows and which parts of HyperFetch it uses.
- Press Run example to start it in your browser, or open it in StackBlitz or CodeSandbox to edit it.
- Copy it locally with
npx tiged BetterTyped/hyper-fetch/examples/<group>/<name> my-app.
The examples live in the examples/ folder of the
repository. They are built and type-checked against the current source on every change, so the code you see here works
with the latest release.
Getting started
Fetch a list and its details with useFetch, typed requests and a shared cache.
Send typed requests from plain TypeScript and read the response object, no framework needed.
Type endpoint and global errors, render a state per status and retry failed requests.
Describe an API once as a typed schema and call it through createSdk with useFetch and useSubmit.
Change staleTime, cacheTime, retry and refetchOnFocus with sliders and watch the cache and the network react.
Set useFetch options once for the whole app with the React Provider, and override them per hook.
Wrap requests in your own typed hooks, usePosts, usePost and useRenamePost, so components stay small.
Test a component that fetches and saves data with Vitest, Testing Library and HyperFetch mocks.
Data fetching
Fetch a user first, then load their posts and todos only once the user id is known.
Page through products with query params, keep the previous page on screen and prefetch the next one.
Load the next page of products as you scroll, with useInfiniteFetch and an IntersectionObserver.
Load pages on demand with a Load more button, start in the middle of a list and see where each page begins.
Search products while typing and send one request per pause with the bounce option of useFetch.
Refetch data on an interval with refresh and refreshTime, and pause polling in background tabs.
Refetch when the window gets focus, loses it or the network comes back, with a log of every trigger.
Load data with React Suspense and handle failed requests in an error boundary with throwOnError.
Read different parts of one cached response with the select option, and re-render only when that part changes.
Prefetch product details on hover with request.send(), so opening them shows cached data at once.
Load several independent requests at once, each with its own loading state, and show a global indicator with useIsFetching.
Keep search, sort and page in the URL query string and turn them into typed query params, with working back and forward.
Send a request only when the user asks: useFetch with disabled, or request.send() for a one-off call.
An infinite list that keeps only three pages with useInfiniteFetch maxPages and loads dropped pages again when you scroll back.
A chat that opens at the newest messages and loads older ones with fetchPreviousPage as you scroll up, keeping your place.
A product table with server-side sorting, search and pagination that keeps the previous rows on screen while the next ones load.
Download a file with a live percentage, speed and time left from onDownloadProgress, then save it from a Blob.
Mutations
Submit a form with useSubmit, a typed payload, a submitting state and the validation errors the server sends back.
Toggle and add todos instantly with setOptimistic, and roll the change back when the server rejects it.
Invalidate cached lists after a mutation so every useFetch that shows them fetches fresh data.
Create, read, update and delete todos, and write each server response into the cached list instead of refetching it.
Upload a file as FormData with useSubmit, follow each phase of the request with progress bars and cancel it with abort.
Delete a todo optimistically, offer Undo for five seconds and send the request only if nobody undoes it, with rollback on failure.
Reorder a list with native drag and drop, update it optimistically and move the item back when the save fails.
Complete or delete many todos at once, one at a time or in parallel, with a progress bar and a result for every row.
Show a real upload percentage, speed and time left with the Axios adapter, and cancel the upload at any point.
Caching
See staleTime, cacheTime and the revalidate option at work, with a live view of what is fresh, stale or removed from the cache.
Edit cached data with client.cache.update and watch every component that reads it, through useFetch or useCache, update at once.
Show a product's details at once with initialResponse taken from the list, then replace them with the server response.
Share a cart between distant components through the HyperFetch cache with useCache and client.cache.update, without props or context.
Send cache changes to every open tab with a BroadcastChannel, so all tabs show the same data without refetching.
Request control
Cancel in-flight requests with abort() and with cancelable requests that stop the previous search when a new one starts.
Retry failed requests with retry and retryTime, and watch every attempt end in a final success or error.
Let many callers that ask for the same data at once share one network request with deduplicate.
Send messages one at a time with queued requests, and start, pause, stop or remove them with useQueue.
Log in, attach the token to every request with onAuth and refresh it on a 401 with onError.
Validate API responses with zod and map them to the app shape with setResponseMapper.
Build a screen before its backend exists with setMock - mocked data, latency, errors and timeouts.
Retry only network errors and 5xx answers, with exponential backoff and jitter, and log every attempt.
Handle 429 Too Many Requests in one client interceptor that waits as long as the Retry-After header says and sends the request again.
Set a timeout per request with the adapter options, show a clear timeout state, and retry with the same or a longer limit.
Write a logging plugin and a metrics plugin that see every request of the client, and show their output live.
Validate the payload with zod in a request mapper, show field errors in the form, and send nothing when the data is invalid.
Give each endpoint its own error type on top of the global one, and narrow the union in the UI to show the right message.
Offline and persistence
Persist both the cache (IndexedDB) and the request queue (localStorage), so the app opens with data and keeps changes made offline across reloads.
Requests made offline wait in the queue and are sent in order when the app is back online.
Persist the cache to localStorage so a reload shows data at once, without a request.
Persist large responses in IndexedDB with the cache lazyStorage, and show them from disk while the API is asked again.
Bump the cache version with a release, so persisted data in an old shape is dropped instead of breaking the new code.
Keep offline mutations in a persistent dispatcher queue, so they survive a page reload and are sent once online.
Realtime and streaming
A chat over WebSocket with useListener and useEmitter, connection state and reconnects.
Listen to a live server-sent events stream with the SSE adapter and useListener, with pause and resume.
Render a streamed HTTP response chunk by chunk with useStream, the way chat apps show an LLM answer.
Load a list once with useFetch and keep its cache current with server-sent events from a local Hono server.
Stream a model answer token by token from a local Hono server with useStream, with stop and regenerate.
Live notifications pushed over server-sent events from a local Hono server, with an unread badge, mark as read and a capped list.
Adapters and integrations
Query a GraphQL API with the GraphQL adapter - typed queries, variables and per-variable caching.
Send HyperFetch requests with axios through the Axios adapter, with axios options and errors passed through.
Connect a client to the HyperFlow devtools with the devtools plugin and inspect requests, cache and queues.
A Hono API and a React client in one Vite app, with requests typed from the Hono routes.
A tRPC router served by Hono and a React client that calls it through HyperFetch with types inferred from the router.
A live chat on tRPC subscriptions, streamed over Server-Sent Events into useListener with typed events and resume support.
A contract-first oRPC API on Hono and a React client typed from the contract, with Dates and typed errors kept end to end.
Stream job progress from an oRPC async generator into useListener over an HTTP event stream, with event ids and typed events.
An Elysia API on Node.js and a React client whose requests, query params and error bodies are typed from the Elysia routes.
Generate typed HyperFetch requests from the Swagger Petstore OpenAPI spec with @hyper-fetch/cli and use them in React.
Create, update and delete with GraphQL mutations and write each result into the cached query instead of fetching it again.
A Firestore guestbook where every read and write is a HyperFetch request, with query constraints, typed documents and errors in the response.
A Node.js script that sends typed requests, runs them in parallel and retries failures, with code that also runs in Bun, Deno and Workers.
Frameworks
Fetch on the server in a Next.js App Router page and hydrate the response into the client cache.
Stream slow server data into a Next.js App Router page section by section with Suspense, and hydrate each section into HyperFetch hooks.
Fetch in getServerSideProps, dehydrate the responses and hydrate them into HyperFetch hooks with one Hydrate in _app.
React Router loaders prefetch through HyperFetch so components read from the cache, and an action saves edits and updates the cache.
TanStack Router loaders fill the HyperFetch cache, and hovering a link prefetches the next page before you click.
Fetch on the server in an Astro page and hydrate the response into a React island that uses HyperFetch hooks.
Apps
Explore the Rick and Morty API with React Router: search and pages in the URL, dependent requests, prefetch on hover and a cache reused on every visit.
A kanban board with native drag and drop, optimistic moves with rollback, a sync status and changes shared between tabs.
A small shop with React Router: catalog with categories, search and infinite scroll, an optimistic cart persisted in localStorage, and a validated checkout.
An admin dashboard with KPI cards from parallel requests, a polled live number, a server-sorted table, an offline banner and errors kept inside each widget.
TodoMVC with a Hono API in the same Vite app: filters in the URL, optimistic toggles and edits, clear completed, and todos stored on the server.