Performance: WebSocket integration
WebSocket integration affects the interaction speed and responsiveness of real-time features by maintaining an open connection for instant data exchange.
useEffect(() => {
const socket = new WebSocket('wss://example.com/socket');
socket.onmessage = event => setUpdates(JSON.parse(event.data));
return () => socket.close();
}, []);useEffect(() => {
const interval = setInterval(() => {
fetch('/api/updates')
.then(res => res.json())
.then(data => setUpdates(data));
}, 3000);
return () => clearInterval(interval);
}, []);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Polling with fetch every few seconds | Multiple DOM updates per fetch | Multiple reflows per update | High paint cost due to frequent updates | [X] Bad |
| WebSocket with event-driven updates | DOM updates only on new data | Single reflow per update | Lower paint cost with fewer updates | [OK] Good |
const socket = new WebSocket('wss://example.com/socket');
socket.onmessage = (event) => {
console.log('Message:', event.data);
};
socket.onopen = () => {
socket.send('Hello server');
};function Chat() {
const socket = new WebSocket('wss://example.com/socket');
socket.onmessage = (e) => console.log(e.data);
return <div>Chat Component</div>;
}Pass the test and this pattern moves unknown