Bird
0
0

What is wrong with this Remix React component WebSocket setup?

medium📝 Debug Q14 of 15
Remix - Advanced Patterns
What is wrong with this Remix React component WebSocket setup?
function Chat() {
  const socket = new WebSocket('wss://example.com/socket');
  socket.onmessage = (e) => console.log(e.data);
  return <div>Chat Component</div>;
}
Aonmessage handler must be async function
BWebSocket should be created inside useEffect to avoid multiple connections
CWebSocket URL must use http instead of wss
DReturn statement should be inside useEffect
Step-by-Step Solution
Solution:
  1. Step 1: Identify WebSocket creation timing

    Creating socket directly in component body causes new connection on every render.
  2. Step 2: Correct usage with useEffect

    useEffect ensures socket is created once and cleaned up on unmount.
  3. Final Answer:

    WebSocket should be created inside useEffect to avoid multiple connections -> Option B
  4. Quick Check:

    Socket creation belongs in useEffect [OK]
Quick Trick: Create sockets in useEffect to prevent repeated connections [OK]
Common Mistakes:
MISTAKES
  • Creating socket outside useEffect causing many connections
  • Thinking onmessage must be async
  • Using http instead of wss for secure WebSocket
  • Placing return inside useEffect

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Remix Quizzes