← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 8 of 10

WebSockets के साथ काम करना

एक WebSocket आपके app और server के बीच एक खुली phone line जैसा है, इसलिए कोई भी side कभी भी बात कर सकती है, हर single message के लिए एक side को call करके hang up करने के बजाय।
Syntax
markup
useEffect(() => {
  const socket = new WebSocket("wss://example.com/socket");
  socket.onmessage = event => setMessages(prev => [...prev, event.data]);
  return () => socket.close();
}, []);

Repeated Fetching के बजाय WebSockets क्यों

fetch() और axios request-response हैं: client हमेशा पहले पूछता है। Real-time data के लिए (जैसे एक live chat या stock ticker), fetch() से repeatedly poll करना wasteful और slow है।

एक WebSocket एक persistent connection खुला रखता है, server को तुरंत नया data available होते ही push करने देते हुए।

Note: WebSockets खासकर तब उपयोग करें जब SERVER को data भेजना initiate करना हो, सिर्फ requests का response देना नहीं।
Warning: WebSockets real complexity जोड़ते हैं (connection management, reconnection logic) — उस data के लिए इनका उपयोग न करें जो rarely update होता है; वहां simple fetching fine है।

उदाहरण: Why WebSockets Instead of Repeated Fetching

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [status] = React.useState("WebSocket connection would open here");
  return <p>{status}</p>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Connection Set Up और Clean Up करना

एक WebSocket connection useEffect के अंदर 'new WebSocket(url)' से बनाया जाता है, और component के unmount होने पर effect के cleanup function में explicitly close किया जाना चाहिए, नहीं तो connection leak होता है और unnecessarily open रहता है।

Note: WebSocket instance को effect के अंदर एक variable में store करें, ताकि cleanup function इसे close करने के लिए same instance reference कर सके।
Warning: cleanup function में ws.close() भूल जाना मतलब इस component का हर remount एक और connection खोलता है, old वालों को कभी बंद किए बिना।

उदाहरण: Setting Up and Cleaning Up the Connection

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [connected, setConnected] = React.useState(false);
  React.useEffect(() => {
    // const ws = new WebSocket("wss://example.com/socket");
    // ws.onopen = () => setConnected(true);
    setConnected(true);
    return () => { /* ws.close(); */ setConnected(false); };
  }, []);
  return <p>{connected ? "Connected" : "Disconnected"}</p>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

onmessage से Messages Receive करना

WebSocket instance का onmessage handler हर बार fire होता है जब server एक नया message push करता है, चाहे client ने इसे मांगा हो या नहीं। इस handler के अंदर state update करना यही है कि कैसे नया data server से आपके React UI में real time में flow करता है।

Note: Server messages आमतौर पर JSON strings के रूप में आते हैं — उपयोग करने से पहले उन्हें JSON.parse(event.data) से parse करें।
Warning: बिना validation के message content को blindly trust और render करना एक security risk हो सकता है अगर message source पूरी तरह trusted न हो।

उदाहरण: Receiving Messages with onmessage

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function App() {
  const [messages, setMessages] = React.useState(["Connected..."]);
  React.useEffect(() => {
    // ws.onmessage = (event) => setMessages(m => [...m, event.data]);
    setTimeout(() => setMessages(m => [...m, "New message from server"]), 500);
  }, []);
  return <ul>{messages.map((m, i) => <li key={i}>{m}</li>)}</ul>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. useEffect के cleanup function में WebSocket connection close करना भूल जाना, component unmount होने पर connections leak करते हुए।
  2. Connection के error/close events handle न करना, connection drop होने पर UI stuck छोड़ते हुए।
  3. Dependency array miss करके हर render पर एक नया WebSocket connection set up करना, एक बार करने के बजाय।
चैप्टर सारांश
  • WebSocket एक server के साथ persistent, two-way connections के लिए built-in browser API है।
  • एक WebSocket connection useEffect के अंदर बनाया और manage किया जाता है, इसके cleanup function में फिर से close किया जाता है।
  • onmessage event handler server से किसी भी समय push किया data receive करता है, सिर्फ एक request के response में नहीं।
  • fetch/axios के विपरीत, WebSockets server को client के पूछे बिना data भेजने देते हैं।
ब्राउज़र सपोर्ट

WebSocket API सभी modern browsers में supported है; किसी भी React version के साथ useEffect के through काम करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.