Implement useEffect on for subscribing to a real-time data stream
Let's consider a real-time example of using useEffect
for subscribing to a real-time data stream. In this example, we'll use the WebSocket
API to connect to a WebSocket server and receive real-time updates.
import React, { useState, useEffect } from 'react';
function RealTimeDataExample() {
// State variable
const [realTimeData, setRealTimeData] = useState(null);
// useEffect for setting up the WebSocket connection
useEffect(() => {
// Create a WebSocket connection
const socket = new WebSocket('wss://example.com/socket');
// Event listener for handling incoming messages
const handleWebSocketMessage = (event) => {
const newData = JSON.parse(event.data);
setRealTimeData(newData);
};
// Event listener for handling errors
const handleWebSocketError = (event) => {
console.error('WebSocket error:', event);
};
// Add event listeners to the WebSocket
socket.addEventListener('message', handleWebSocketMessage);
socket.addEventListener('error', handleWebSocketError);
// Clean-up function (componentWillUnmount)
return () => {
// Close the WebSocket connection when the component is unmounted
socket.close();
};
}, []); // Empty dependency array means this effect runs once after the initial render
// Render based on real-time data
return (
<div>
<h1>Real-Time Data</h1>
{realTimeData ? (
<pre>{JSON.stringify(realTimeData, null, 2)}</pre>
) : (
<p>Waiting for real-time updates...</p>
)}
</div>
);
}
export default RealTimeDataExample;
In this example:
We have a component
RealTimeDataExample
that connects to a WebSocket server using theWebSocket
API.The
useEffect
hook is used to set up the WebSocket connection. It adds event listeners for handling incoming messages and errors.The
handleWebSocketMessage
function parses the incoming JSON data and updates the component's state with the real-time data.The clean-up function (
return () => {...}
) ensures that the WebSocket connection is closed when the component is unmounted.
Conclusion:
This example demonstrates how useEffect
can be used to handle real-time updates, such as those from a WebSocket or other asynchronous data sources. The component sets up the connection when it mounts and cleans up the connection when it unmounts.