Blog>
Snippets

Live Updates from a WebSocket Connection

Show how to synchronize a React component with live data from a WebSocket connection using useSyncExternalStore.
import { useState, useEffect, useLayoutEffect, useCallback } from 'react';
import { useSyncExternalStore } from 'react';

// Creating a WebSocket connection
const ws = new WebSocket('wss://your-websocket-server.com');

// React component that uses the useSyncExternalStore hook to synchronize with live WebSocket data
function LiveUpdatesComponent() {
    // Set an initial state for your data
    const [data, setData] = useState(null);

    const subscribe = useCallback((handleChange) => {
        // Listen for messages on the WebSocket
        ws.onmessage = (event) => {
            const messageData = JSON.parse(event.data);
            setData(messageData);
            handleChange();
        };
        // Provide a way to unsubscribe to the event
        return () => {
            ws.onmessage = null;
        };
    }, []);

    const getSnapshot = useCallback(() => data, [data]);

    // Using useSyncExternalStore to subscribe to external data updates
    const store = useSyncExternalStore(subscribe, getSnapshot);

    // Render your component with the live data
    return (
        <div>
            {store ? JSON.stringify(store) : 'Waiting for data...'}
        </div>
    );
}

export default LiveUpdatesComponent;
The given code defines a React component named 'LiveUpdatesComponent' that synchronizes its state with live data from a WebSocket connection using the useSyncExternalStore hook. A WebSocket connection is created to the specified server URL. The useSyncExternalStore is used within the component to create a 'store' that remains in sync with the external data source. The subscribe function is passed to useSyncExternalStore to listen for incoming WebSocket messages and update the component state accordingly. The data is displayed within a div element, or a placeholder text 'Waiting for data...' if the data is not yet received.