Blog>
Snippets

Implementing Real-Time Data Updates

Use useEffect alongside WebSocket API to fetch real-time data and update the chart dynamically without causing re-render issues.
const [chartData, setChartData] = useState([]);
Initialize the chart data state using React's useState hook to store the data that will be displayed on the chart.
useEffect(() => {
  const ws = new WebSocket('ws://example.com/data');
  ws.onmessage = (event) => {
    const newData = JSON.parse(event.data);
    setChartData(currentData => [...currentData, newData]);
  };

  return () => ws.close();
}, []);
Use the useEffect hook to establish a WebSocket connection when the component mounts. Listen for messages on the WebSocket and update the chart data state with the new data received. Clean up by closing the WebSocket connection when the component unmounts.
/* In your chart component, use the chartData state for displaying the data. */
Reminder to use the chartData state for rendering your chart. This approach ensures the chart updates in real-time as new data is received without unnecessary re-renders.