Careeroza
Real World Example
Real World: Live stock prices over a WebSocket
A trading app (Zerodha, Groww) subscribes to live prices. If the socket is not closed when the user leaves the page or switches stock, old subscriptions keep running and memory grows.
function LivePrice({ symbol }) {
const [price, setPrice] = useState(null);
useEffect(() => {
const socket = new WebSocket('wss://prices.example.com/' + symbol);
socket.onmessage = (e) => setPrice(JSON.parse(e.data).price);
return () => socket.close(); // without this: one more open socket per stock you view
}, [symbol]);
return <p>{symbol}: ₹{price ?? '...'}</p>;
}