WebSocket integration lets your Remix app talk to the server instantly without reloading the page. It helps build live features like chat or notifications.
WebSocket integration in 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.
const socket = new WebSocket('wss://example.com/socket');
socket.onmessage = (event) => console.log(event.data);useEffect(() => {
const socket = new WebSocket('wss://example.com/socket');
socket.onopen = () => socket.send('Hello Server');
return () => socket.close();
}, []);const [count, setCount] = useState(0); useEffect(() => { const socket = new WebSocket('wss://example.com/socket'); socket.onmessage = (event) => setCount(prev => prev + 1); return () => socket.close(); }, []);
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.
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> ); }
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.
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.