Skip to main content

Lesson 5 of 9

WebSockets - Real-Time Data

Real-time features (chat, live scores, collaborative editing, stock tickers) require WebSockets. The browser-standard WebSocket API works in React Native. The main challenges are reconnection logic, cleanup on unmount, and coexistence with TanStack Query.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

useWebSocket Hook

useWebSocket Hook
import { useState, useEffect, useRef, useCallback } from 'react';

type WsStatus = 'connecting' | 'open' | 'closing' | 'closed' | 'error';

interface WebSocketOptions {
  url: string;
  onMessage: (data: unknown) => void;
  reconnectDelay?: number;
  maxReconnects?: number;
}

export function useWebSocket({ url, onMessage, reconnectDelay = 3000, maxReconnects = 5 }: WebSocketOptions) {
  const wsRef = useRef<WebSocket | null>(null);
  const reconnectCount = useRef(0);
  const reconnectTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [status, setStatus] = useState<WsStatus>('connecting');

  const connect = useCallback(() => {
    if (wsRef.current?.readyState === WebSocket.OPEN) return;

    const ws = new WebSocket(url);
    wsRef.current = ws;
    setStatus('connecting');

    ws.onopen = () => {
      setStatus('open');
      reconnectCount.current = 0; // reset on successful connection
    };

    ws.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data as string);
        onMessage(data);
      } catch { /* ignore malformed messages */ }
    };

    ws.onerror = () => setStatus('error');

    ws.onclose = () => {
      setStatus('closed');
      // Auto-reconnect with backoff
      if (reconnectCount.current < maxReconnects) {
        reconnectCount.current++;
        const delay = reconnectDelay * Math.min(reconnectCount.current, 4);
        reconnectTimer.current = setTimeout(connect, delay);
      }
    };
  }, [url, onMessage, reconnectDelay, maxReconnects]);

  useEffect(() => {
    connect();
    return () => {
      if (reconnectTimer.current) clearTimeout(reconnectTimer.current);
      wsRef.current?.close();
    };
  }, [connect]);

  const send = useCallback((data: unknown) => {
    if (wsRef.current?.readyState === WebSocket.OPEN) {
      wsRef.current.send(JSON.stringify(data));
    }
  }, []);

  return { status, send };
}

// ---- Usage: Live chat ----
interface ChatMessage { id: string; userId: string; text: string; timestamp: number; }

function ChatRoom({ roomId }: { roomId: string }) {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const listRef = useRef<FlatList>(null);

  const handleMessage = useCallback((data: unknown) => {
    const msg = data as ChatMessage;
    setMessages(prev => [...prev, msg]);
    // Scroll to new message
    setTimeout(() => listRef.current?.scrollToEnd({ animated: true }), 100);
  }, []);

  const { status, send } = useWebSocket({
    url: `wss://api.example.com/chat/${roomId}`,
    onMessage: handleMessage,
  });

  function sendMessage() {
    if (!input.trim() || status !== 'open') return;
    send({ type: 'message', text: input.trim() });
    setInput('');
  }

  return (
    <View style={{ flex: 1 }}>
      <Text style={{ color: status === 'open' ? '#4ade80' : '#f87171', padding: 8, fontSize: 12 }}>
        โ— {status}
      </Text>
      <FlatList
        ref={listRef}
        data={messages}
        keyExtractor={m => m.id}
        renderItem={({ item }) => (
          <View style={{ padding: 12, marginHorizontal: 16, marginVertical: 4, backgroundColor: '#1e293b', borderRadius: 10 }}>
            <Text style={{ color: '#229c6b', fontSize: 12, marginBottom: 2 }}>User {item.userId}</Text>
            <Text style={{ color: '#f1f5f9' }}>{item.text}</Text>
          </View>
        )}
      />
      <View style={{ flexDirection: 'row', padding: 16, gap: 8 }}>
        <TextInput value={input} onChangeText={setInput} placeholder="Type a message..." placeholderTextColor="#475569"
          style={{ flex: 1, backgroundColor: '#1e293b', borderRadius: 10, padding: 12, color: '#f1f5f9' }}
          onSubmitEditing={sendMessage} returnKeyType="send" />
        <Pressable onPress={sendMessage} style={{ backgroundColor: '#229c6b', width: 44, borderRadius: 10, alignItems: 'center', justifyContent: 'center' }}>
          <Text style={{ color: 'white', fontSize: 18 }}>โ†‘</Text>
        </Pressable>
      </View>
    </View>
  );
}

Tip

Tip

Practice WebSockets RealTime Data in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Persistent WebSocket connections, heartbeats, and AppState reconnection handling

Practice Task

Note

Practice Task - (1) Write a working example of WebSockets RealTime Data from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with WebSockets RealTime Data is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react native code.

Topics in This Module

0/9 done