0
0
Remixframework~5 mins

WebSocket integration in Remix

Choose your learning style9 modes available
Introduction

WebSocket integration lets your Remix app talk to the server instantly without reloading the page. It helps build live features like chat or notifications.

You want to show live chat messages as they arrive.
You need real-time updates like stock prices or sports scores.
You want to notify users instantly about new events or alerts.
You are building a multiplayer game that needs fast communication.
You want to sync data between users without refreshing the page.
Syntax
Remix
import { useEffect, useState } from 'react';

export default function WebSocketComponent() {
  const [messages, setMessages] = useState([]);

  useEffect(() => {
    const socket = new WebSocket('wss://example.com/socket');

    socket.onmessage = (event) => {
      setMessages(prev => [...prev, event.data]);
    };

    return () => {
      socket.close();
    };
  }, []);

  return (
    <ul>
      {messages.map((msg, i) => <li key={i}>{msg}</li>)}
    </ul>
  );
}

Use useEffect to open and close the WebSocket connection properly.

Update state inside onmessage to show new data instantly.

Examples
Basic WebSocket connection that logs messages from the server.
Remix
const socket = new WebSocket('wss://example.com/socket');
socket.onmessage = (event) => console.log(event.data);
Send a message to the server once the connection opens, then clean up on unmount.
Remix
useEffect(() => {
  const socket = new WebSocket('wss://example.com/socket');
  socket.onopen = () => socket.send('Hello Server');
  return () => socket.close();
}, []);
Count how many messages have been received in real-time.
Remix
const [count, setCount] = useState(0);
useEffect(() => {
  const socket = new WebSocket('wss://example.com/socket');
  socket.onmessage = (event) => setCount(prev => prev + 1);
  return () => socket.close();
}, []);
Sample Program

This component connects to a public echo WebSocket server. It shows messages sent and received live. You can type a message and send it by clicking the button or pressing Enter. The server echoes back your message, so you see it twice with labels.

ARIA labels and live region help screen readers know about updates.

Remix
import { useEffect, useState, useRef } from 'react';

export default function LiveChat() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const socketRef = useRef(null);

  useEffect(() => {
    socketRef.current = new WebSocket('wss://echo.websocket.org');

    socketRef.current.onmessage = (event) => {
      setMessages(prev => [...prev, `Server: ${event.data}`]);
    };

    return () => {
      socketRef.current.close();
    };
  }, []);

  function sendMessage() {
    if (!input || !socketRef.current || socketRef.current.readyState !== WebSocket.OPEN) return;
    socketRef.current.send(input);
    setMessages(prev => [...prev, `You: ${input}`]);
    setInput('');
  }

  return (
    <main>
      <h1>Live Chat</h1>
      <ul aria-live="polite">
        {messages.map((msg, i) => <li key={i}>{msg}</li>)}
      </ul>
      <input
        type="text"
        aria-label="Message input"
        value={input}
        onChange={e => setInput(e.target.value)}
        onKeyDown={e => e.key === 'Enter' && sendMessage()}
      />
      <button onClick={sendMessage} aria-label="Send message">Send</button>
    </main>
  );
}
OutputSuccess
Important Notes

WebSocket URLs start with wss:// for secure connections.

Always close the socket in cleanup to avoid memory leaks.

Use aria-live="polite" on message lists for accessibility.

Summary

WebSocket integration allows real-time two-way communication in Remix apps.

Use useEffect to manage socket lifecycle and update state on messages.

Good for live chat, notifications, and instant updates without page reloads.