Real-Time Counter with WebSockets in React (TypeScript)
This challenge focuses on implementing a real-time counter application using React and WebSockets. The counter should display a value that is updated in real-time based on messages received from a WebSocket server, allowing multiple users to see the same updated count simultaneously. This is a common pattern for collaborative applications, live dashboards, and chat applications.
Problem Description
You are tasked with building a React component that displays a counter and updates it in real-time based on messages received from a WebSocket server. The component should:
- Establish a WebSocket connection: Connect to a WebSocket server at
ws://localhost:8080upon component mount. - Handle incoming messages: Listen for messages from the server. When a message is received, parse the message as a number and update the counter's state with this new value.
- Display the counter: Render the current counter value in the UI.
- Close the WebSocket connection: Close the WebSocket connection when the component unmounts to prevent memory leaks.
- Error Handling: Gracefully handle WebSocket connection errors (e.g., server unavailable) and display an appropriate error message to the user.
Key Requirements:
- Use TypeScript for type safety.
- Utilize React's
useStatehook to manage the counter's state. - Implement proper error handling for WebSocket connections.
- Ensure the component is clean, readable, and well-structured.
Expected Behavior:
- Upon mounting, the component should attempt to connect to the WebSocket server.
- If the connection is successful, the component should display an initial counter value (e.g., 0).
- When the server sends a message containing a number, the counter value in the UI should update immediately.
- If the connection fails, an error message should be displayed to the user.
- Upon unmounting, the WebSocket connection should be closed.
Edge Cases to Consider:
- Server is unavailable or unreachable.
- Messages received from the server are not valid numbers. (Handle gracefully, perhaps by logging an error and ignoring the message).
- Network connectivity issues during the application's lifecycle.
Examples
Example 1:
Input: WebSocket server running at ws://localhost:8080 sending messages: [1, 2, 5, 10]
Output: The React component displays the counter values: 1, 2, 5, 10 sequentially.
Explanation: The component connects to the server, receives the messages, and updates the state accordingly, causing the UI to re-render with the new values.
Example 2:
Input: WebSocket server is unavailable.
Output: The React component displays an error message like "Failed to connect to WebSocket server."
Explanation: The component attempts to connect but fails, triggering the error handling logic and displaying an appropriate message to the user.
Example 3:
Input: WebSocket server sends a message that is not a number (e.g., "hello").
Output: The component continues to display the previous counter value and logs an error to the console (or handles it silently). The UI does not crash.
Explanation: The component receives an invalid message, detects it's not a number, and ignores it, preventing errors and maintaining the application's stability.
Constraints
- The WebSocket server address is fixed at
ws://localhost:8080. You are not responsible for setting up the server; assume it exists and is running. - The messages sent by the server are expected to be strings that can be parsed as numbers.
- The counter value should always be a non-negative integer.
- The component should render within a reasonable timeframe (e.g., less than 100ms) even with frequent updates.
Notes
- Consider using
useEffectto manage the WebSocket connection lifecycle (mounting and unmounting). - Use
try...catchblocks to handle potential errors during WebSocket connection and message parsing. - Think about how to provide feedback to the user about the connection status (e.g., connecting, connected, disconnected).
- You can use a library like
axiosorfetchto make the WebSocket connection, but the core logic should be implemented using the native WebSocket API. Focus on the React component's behavior and state management. - The server is expected to send messages as plain text strings representing numbers. No JSON or other formatting is expected.