Skip to main content

Overview

The useChatSimulator hook automatically generates simulated incoming messages at regular intervals to demonstrate chat functionality. It shows typing indicators before messages appear and randomly sends either text or media messages.

Usage

import { useChatSimulator } from "@/hooks/use-chat-simulator"

function ChatDemo() {
  // Hook runs automatically when component mounts
  useChatSimulator()
  
  return <ChatInterface />
}
This hook is designed for demo and preview environments. It should not be used in production applications with real chat data.

Signature

function useChatSimulator(): void

Return value

This hook does not return any value. It manages side effects internally.

Behavior

The hook performs the following actions:
  1. Message generation interval: Every 18 seconds, picks a random chat and contact
  2. Typing indicator: Shows the contact is typing for 2.2-4 seconds
  3. Message type: 75% chance of text message, 25% chance of media message
  4. Cleanup: Clears all intervals and timers when the component unmounts

Text messages

Randomly selects from these response snippets:
  • “Just synced the latest updates – take a look when you can.”
  • “Love where this is headed!”
  • “I’ll package these assets and drop them in a bit.”
  • “Can we align on the microcopy before handoff?”
  • “Here’s a quick mock to illustrate the interaction.”

Media messages

Sends image messages with sample URLs and captions from a predefined set of design-related content.

Dependencies

This hook relies on the chat store from @/lib/chat/state and uses the following store methods:
contacts
Record<string, Contact>
Contact data from the chat store
chats
Record<string, Chat>
Active chats from the chat store
receiveMessage
function
Function to add a new message to a chat
setTypingIndicator
function
Function to show/hide typing indicators

Implementation details

const interval = setInterval(() => {
  const chat = pickChat(chatList, contacts)
  if (!chat) return
  const contact = contacts[chat.contactId]
  if (!contact) return

  setTypingIndicator(chat.id, contact.id, true)

  const duration = 2200 + Math.random() * 1800
  setTimeout(() => {
    setTypingIndicator(chat.id, contact.id, false)
    const message = Math.random() > 0.75
      ? createInboundMediaMessage({...})
      : createInboundTextMessage({...})
    receiveMessage(chat.id, message)
  }, duration)
}, 18000)
The hook automatically cleans up all timers and intervals when the component unmounts to prevent memory leaks.

Source

See the full implementation in hooks/use-chat-simulator.ts:32

Build docs developers (and LLMs) love