Skip to content

React API ​

ts
import { FetchProvider, useFetch, useSse, useWs } from 'tanstack-fetch/react'
ExportRole
FetchProviderOptional shared client via context
useFetch()Read client from FetchProvider
useSse(path, options)React SSE helper (needs SSE client)
useWs(path, options)WebSocket / WebTransport hook (needs tanstack-fetch/live client)

useSse result ​

FieldType
dataLast message payload
eventLast full SSE event
errorLast error
status'connecting' | 'connected' | 'disconnected' | 'error'
closeStop the stream

useSse options ​

OptionRole
clientSSE client from tanstack-fetch/sse (preferred — no provider)
enabledWhen false, stays disconnected

Example (no provider) ​

tsx
import { createFetch } from 'tanstack-fetch/sse'
import { useSse } from 'tanstack-fetch/react'

const api = createFetch({
  plugins: ['sse-resume'],
  getToken: () => localStorage.getItem('access_token'),
})

const OrdersLive = () => {
  const { data, status, error, close } = useSse<{ id: string }>('/orders/stream', {
    client: api,
  })

  if (status === 'connecting') return <p>Connecting…</p>
  if (status === 'error') return <p>{error?.message}</p>

  return (
    <div>
      <p>{status}</p>
      <pre>{JSON.stringify(data, null, 2)}</pre>
      <button type="button" onClick={close}>
        Disconnect
      </button>
    </div>
  )
}

useWs result ​

FieldType
datalast message (JSON parsed)
errorlast error
status'connecting' | 'connected' | 'disconnected' | 'error'
sendSend a message (queued until open, JSON for objects)
closeClose and stop reconnecting

useWs options ​

Generics: useWs<Message, Params, Send> and useSse<Message, Params> — params is typed from the path like api.get (use NoParams to skip to Send).

All api.ws options (authIn, reconnect, protocols, transport, params, query, …), plus:

OptionRole
clientClient from tanstack-fetch/live (preferred)
enabledWhen false, stays disconnected

Live demo: SSE — useSse · React guide

MIT Licensed · Created by Mohammad Garmabi · Not an official TanStack package