Helper
Conversation API

React Client SDK Reference

React hooks and components for integrating Helper into your React applications

React Hooks Reference

The Helper React package provides a collection of React hooks and components that make it easy to integrate Helper's chat capabilities into your React applications. Built on top of the Client SDK, these hooks provide reactive state management using React Query.

Installation

bash npm install @helper/react @ai-sdk/react

Setup

Provider Setup

Wrap your application (or just your support portal) with the HelperClientProvider to provide the Helper client to all child components:

"use server";
 
import { HelperClientProvider } from "@helper/react";
 
function App() {
  // Make sure this runs on the server; you may need an API if you aren't using server components
  const { session } = generateHelperAuth({ email: "john@example.com", hmacSecret: "YOUR_HMAC_SECRET" });
 
  return (
    <HelperClientProvider host="https://your-helper-instance.com" session={session}>
      <YourAppContent />
    </HelperClientProvider>
  );
}

Provider Props

ParameterTypeRequiredDescription
hoststringThe base URL of your Helper instance
sessionSessionParamsSession configuration (same as Client SDK)
childrenReactNodeYour application components
queryClientQueryClientCustom React Query client (optional)

The provider automatically creates and manages a React Query client if you don't provide one. All hooks use this shared client for caching and synchronization.

Conversation Hooks

useConversations()

Retrieves all conversations for the current session with automatic caching and background updates.

Parameters:

useConversations(queryOptions?: Partial<UseQueryOptions<ConversationsResult>>)

Returns: A React Query object with conversation data.

Example:

import { useConversations } from "@helper/react";
 
function ConversationsList() {
  const { data: conversations, isLoading, error } = useConversations();
 
  if (isLoading) return <div>Loading conversations...</div>;
  if (error) return <div>Error loading conversations</div>;
 
  return (
    <div>
      {conversations?.conversations.map((conv) => (
        <div key={conv.slug}>
          <h3>{conv.subject}</h3>
          <p>{conv.latestMessage}</p>
        </div>
      ))}
    </div>
  );
}

useConversation(slug, options?, queryOptions?)

Retrieves a specific conversation with real-time updates and automatic read marking.

Parameters:

  • slug (string): The conversation identifier
  • options (object, optional):
    • markRead (boolean, default: true): Whether to mark as read when fetched
    • enableRealtime (boolean, default: true): Enable real-time updates
  • queryOptions: React Query options

Returns: A React Query object with conversation details.

Example:

import { useConversation } from "@helper/react";
 
function ConversationView({ slug }: { slug: string }) {
  const { data: conversation, isLoading } = useConversation(slug, {
    enableRealtime: true,
    markRead: true,
  });
 
  if (isLoading) return <div>Loading conversation...</div>;
 
  return (
    <div>
      <h2>{conversation?.subject}</h2>
      {conversation?.messages.map((message) => (
        <div key={message.id}>
          <strong>{message.role}:</strong> {message.content}
        </div>
      ))}
    </div>
  );
}

useUnreadConversationsCount()

Retrieves the count of unread conversations with automatic updates.

Parameters:

useUnreadConversationsCount(queryOptions?: Partial<UseQueryOptions<UnreadConversationsCountResult>>)

Returns: A React Query object with unread count.

Example:

import { useUnreadConversationsCount } from "@helper/react";
 
function UnreadBadge() {
  const { data } = useUnreadConversationsCount();
 
  if (!data?.count) return null;
 
  return <span className="badge">{data.count}</span>;
}

useCreateConversation()

Mutation hook for creating new conversations.

Parameters:

useCreateConversation(mutationOptions?: Partial<UseMutationOptions<any, Error, CreateConversationParams>>)

Returns: A React Query mutation object.

Example:

import { useCreateConversation } from "@helper/react";
 
function NewConversationButton() {
  const createConversation = useCreateConversation({
    onSuccess: (data) => {
      console.log("Created conversation:", data.conversationSlug);
    },
  });
 
  const handleCreate = () => {
    createConversation.mutate({
      subject: "New Support Request",
      isPrompt: false,
    });
  };
 
  return (
    <button onClick={handleCreate} disabled={createConversation.isPending}>
      {createConversation.isPending ? "Creating..." : "New Conversation"}
    </button>
  );
}

useUpdateConversation()

Mutation hook for updating existing conversations.

Parameters:

useUpdateConversation(mutationOptions?: Partial<UseMutationOptions<any, Error, { slug: string; params: UpdateConversationParams }>>)

Returns: A React Query mutation object.

Example:

import { useUpdateConversation } from "@helper/react";
 
function MarkReadButton({ slug }: { slug: string }) {
  const updateConversation = useUpdateConversation();
 
  const markAsRead = () => {
    updateConversation.mutate({
      slug,
      params: { markRead: true },
    });
  };
 
  return <button onClick={markAsRead}>Mark as Read</button>;
}

Chat Hook

useChat(options)

Provides a complete chat interface with real-time messaging, typing indicators, and tool integration.

Parameters:

interface UseChatProps {
  conversation: ConversationDetails;
  tools?: Record<string, HelperTool>;
  enableRealtime?: boolean;
  ai?: Parameters<typeof useChat>[0]; // AI SDK options
}

Returns:

{
  messages: Message[];
  setMessages: (messages: Message[]) => void;
  agentTyping: boolean;
  input: string;
  handleInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
  handleSubmit: (e?: React.FormEvent<HTMLFormElement>) => void;
  isLoading: boolean;
  error: Error | undefined;
}

Example:

import { useChat, useConversation } from "@helper/react";
 
function ChatInterface({ conversationSlug }: { conversationSlug: string }) {
  const { data: conversation } = useConversation(conversationSlug);
 
  const { messages, input, handleInputChange, handleSubmit, agentTyping, isLoading } = useChat({
    conversation: conversation!,
    enableRealtime: true,
    tools: {
      searchDocs: {
        description: "Search documentation",
        parameters: {
          query: { type: "string", optional: false },
        },
        execute: async (args) => {
          return await searchDocumentation(args.query);
        },
      },
    },
  });
 
  if (!conversation) return <div>Loading...</div>;
 
  return (
    <div className="chat-container">
      <div className="messages">
        {messages.map((message) => (
          <div key={message.id} className={`message ${message.role}`}>
            {message.content}
          </div>
        ))}
        {agentTyping && <div className="typing">Agent is typing...</div>}
      </div>
 
      <form onSubmit={handleSubmit}>
        <input value={input} onChange={handleInputChange} placeholder="Type your message..." />
        <button type="submit" disabled={isLoading}>
          Send
        </button>
      </form>
    </div>
  );
}

Session Hook

useCreateSession()

Mutation hook for creating new sessions (rarely needed as the provider handles this automatically).

Parameters:

useCreateSession(mutationOptions?: Partial<UseMutationOptions<any, Error, SessionParams>>)

Returns: A React Query mutation object.

Example:

import { useCreateSession } from "@helper/react";
 
function SessionManager() {
  const createSession = useCreateSession({
    onSuccess: (data) => {
      console.log("Session created:", data.token);
    },
  });
 
  const handleCreateSession = () => {
    createSession.mutate({
      email: "user@example.com",
      customerMetadata: {
        name: "User Name",
      },
    });
  };
 
  return <button onClick={handleCreateSession}>Create Session</button>;
}

Real-time Features

The React hooks automatically handle real-time updates when enableRealtime is true (default):

  • Conversation updates: Subject changes, new messages from agents
  • Typing indicators: Shows when agents are typing
  • Message synchronization: Automatically syncs new messages across all components

Real-time features use WebSocket connections managed by the underlying Helper Client SDK. The connections are automatically established and cleaned up when components mount and unmount.

Error Handling

All hooks return standard React Query error states:

function MyComponent() {
  const { data, error, isLoading, isError } = useConversations();
 
  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error: {error?.message}</div>;
 
  return <div>{/* Your content */}</div>;
}

TypeScript Support

All hooks are fully typed with TypeScript. Import types as needed:

import type {
  ConversationDetails,
  CreateConversationParams,
  HelperTool,
  SessionParams,
  UpdateConversationParams,
} from "@helper/client";
import type { HelperClientProviderProps, UseChatProps } from "@helper/react";

Best Practices

  1. Provider Placement: Place HelperClientProvider as high as possible in your component tree
  2. Real-time: Enable real-time features for better user experience
  3. Error Boundaries: Wrap components in error boundaries to handle API failures gracefully
  4. Loading States: Always handle loading and error states in your UI
  5. Query Invalidation: The hooks automatically invalidate related queries when data changes