React
react ai hooks

useStream

React hook for handling AI streaming responses with automatic chunk processing and state management.

import { useState, useCallback } from 'react';

export function useStream() {
  const [data, setData] = useState('');
  const [isStreaming, setIsStreaming] = useState(false);

  const stream = useCallback(async (url: string, body: any) => {
    setIsStreaming(true);
    try {
      const response = await fetch(url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body)
      });
      
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();

      if (!reader) return;

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;
        
        const chunk = decoder.decode(value);
        setData(prev => prev + chunk);
      }
    } finally {
      setIsStreaming(false);
    }
  }, []);

  return { data, stream, isStreaming };
}