Bidirectional communication using WebSockets for real-time messaging with connection management.
This demo simulates a WebSocket connection for real-time bidirectional communication. In production, this would connect to a real WebSocket server.
Bidirectional data flow between client and server
Automatic reconnection and connection state tracking
Instant message delivery without polling
Handles thousands of concurrent connections
• Live chat applications
• Real-time notifications
• Collaborative editing
• Live sports scores
• Stock market tickers
• Multiplayer games
const useWebSocket = (url: string) => {
const [messages, setMessages] = useState([])
const ws = useRef<WebSocket | null>(null)
useEffect(() => {
ws.current = new WebSocket(url)
ws.current.onmessage = (event) => {
setMessages(prev => [...prev, event.data])
}
return () => ws.current?.close()
}, [url])
const sendMessage = (msg: string) => {
ws.current?.send(msg)
}
return { messages, sendMessage }
}