Establishing a WebSocket Connection in React

Show how to open a WebSocket connection using the useEffect hook in a React functional component.
import React, { useEffect } from 'react';
Import useEffect from React to work within the functional component.
const WebSocketComponent = () => {
Define a functional React component.
useEffect(() => {
useEffect hook to handle component lifecycle events.
const socket = new WebSocket('ws://');
Creating a new WebSocket connection to the server.
socket.onopen = () => { console.log('WebSocket connection established.'); };
Handle the open event of the WebSocket connection.
socket.onmessage = (event) => { console.log('Message from server:',; };
Handle messages received from the server.
socket.onclose = () => { console.log('WebSocket connection closed.'); };
Cleanup when the WebSocket connection is closed.
return () => { socket.close(); };
Clean up function to close WebSocket connection when the component unmounts.
}, []);
The empty array as the second argument means this effect runs only on component mount and unmount.
return (<div>WebSocket Component</div>);
Render method of the component, which would be more elaborate in a real application.
Closing bracket for the component function.
export default WebSocketComponent;
Exporting the component for use in other parts of the application.