Network & RealtimeAdvancedSSR-safehooks/network/useSSE.ts

useSSE

Alias of useEventSource.

Import

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

API

Signature

useSSE(url, options?)

When to use

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

SSR / Next.js

Connect only in the browser / Client Components.

Live playground

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

Live playgroundEdit · run with real @/hooks · useSSE
Editor
function Stream() {
  const { lastEvent, status } = useSSE('/api/events');
  return <p>{status}: {lastEvent?.data}</p>;
}
Preview

Implementation source

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

hooks/network/useSSE.ts
import {
  useEventSource,
  type UseEventSourceOptions,
} from './useEventSource';

/** Alias of {@link useEventSource}. */
export function useSSE(
  url: string | null | undefined,
  options?: UseEventSourceOptions,
) {
  return useEventSource(url, options);
}

Copy-paste example

useSSE.example.tsx
'use client';

import { useSSE } from '@/hooks';

export function Stream() {
  const { lastEvent, status } = useSSE('/api/events');
  return <p>{status}: {lastEvent?.data}</p>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Never hardcode URLs in components shared across envs — use env vars.
  • Source of truth: open hooks/network/useSSE.ts for implementation details