How would you design a real-time chat application in React?

Build a scalable real-time chat UI using WebSockets, presence indicators, message queues, retries, and optimistic rendering.

advancedUi patternsreactchatwebsocketreal-time
Published: 11/23/2025
Updated: 11/23/2025

Advertisement

đź§© Scenario

You're building a WhatsApp/Slack-style chat UI with React. Requirements:

  • Real-time messages using WebSockets
  • Show online/offline presence
  • Optimistic rendering of outgoing messages
  • Auto-retry on connection drop
  • Message history built from REST API + live updates
  • Typing indicators
  • Handle unread counts & scroll-to-latest

đź§  Answer (Design Overview)

Core Architecture

  1. Transport Layer: WebSockets
    Use a dedicated client (new WebSocket(url)) or a wrapper library. Reconnect with backoff.

  2. Message Pipeline (client-side):

    • REST: load recent messages
    • WS: subscribe to message events
    • Optimistic: append message locally before sending
    • Retry: if send fails after a timeout
  3. State Management:

    • A store using Zustand/Redux or React Context
    • Messages array + pendingMessages + deliveredMessages
  4. Presence & Typing Indicators:

    • WebSocket events like { type: 'typing', userId }
    • Mark users online via periodic heartbeats
  5. Scroll Handling:

    • Scroll to bottom on new outgoing message
    • Only auto-scroll if user is near bottom (Slack behavior)
  6. Retries & Reconnection:

    • Exponential backoff
    • Queue outgoing messages until connected

Tradeoffs:

  • WebSockets scale well, but require server infra.
  • Long-lived connections require heartbeat/ping.

🎮 Live Demo: Real-time Chat Application


🔍 Real-World Tips

  • Store chat history in an indexed DB for offline usage.
  • Use server timestamps to order messages.
  • Implement message deduplication using message IDs.
  • Use presence events to show green "online" badges.
  • Paginate history using cursor-based pagination.

Quick Practice

  1. Add typing indicators using WS events.
  2. Add presence tracking with heartbeat events.
  3. Add a retry system for failed outgoing messages.
  4. Cache last 50 messages in localStorage.

Summary

  • Real-time chat requires WebSockets + reconnection logic.
  • Use optimistic UI and a message queue for outgoing messages.
  • Add presence, typing, and scroll behavior for a production-ready UX.
Frequently Asked Questions

Why use WebSockets instead of polling?

WebSockets provide bidirectional real-time communication with lower latency and fewer network round-trips.

How do you handle offline users?

Queue messages locally, retry on reconnect, and use presence sync to update UI states.

Advertisement


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.

Advertisement