stream hooks / Getting started

Getting Started

Installation

To start using stream-hooks in your React project, you can install it using your preferred package manager. Below are the commands for npm, pnpm, and yarn.

With npm

npm install stream-hooks zod zod-stream

With pnpm

pnpm add stream-hooks zod zod-stream

With bun

bun add stream-hooks zod zod-stream

Basic Setup

Once stream-hooks is installed in your project, you can start using the hooks in your React components. Ensure you have React set up in your project as stream-hooks is designed to work within a React environment.

Using useStream

import React from 'react';
import { useStream } from 'stream-hooks';
 
const MyComponent = () => {
  const { startStream, stopStream } = useStream({
    onBeforeStart: () => console.log('Stream is about to start'),
    onStop: () => console.log('Stream has stopped')
  });
 
  // Start and stop stream based on component lifecycle or user interactions
  // ...
 
  return (
    <div>
      <button onClick={() => startStream({ url: 'http://example.com/stream' })}>Start Stream</button>
      <button onClick={stopStream}>Stop Stream</button>
    </div>
  );
};
 
export default MyComponent;

Using useJsonStream

import React from 'react';
import { useJsonStream } from 'stream-hooks';
import { z } from 'zod';
 
const MyJsonComponent = () => {
  const schema = z.object({
    message: z.string(),
  });
 
  const {
    data,
    startStream,
    stopStream,
    loading
  } = useJsonStream({
    schema,
    onBeforeStart: () => console.log('JSON stream is about to start'),
    onStop: () => console.log('JSON stream has stopped'),
    onReceive: (json) => console.log('Received data:', json)
  });
 
  // Start and stop stream based on component lifecycle or user interactions
  // ...
 
  return (
    <div>
      <button onClick={() => startStream({ url: 'http://example.com/jsonstream' })}>Start JSON Stream</button>
      <button onClick={stopStream}>Stop JSON Stream</button>
      {loading && <p>Loading...</p>}
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
};
 
export default MyJsonComponent;