State Synchronization: Optimistic UI & WebSockets
On this page
Real-time State Synchronization
Modern apps feel alive. If a colleague updates a document, you see the changes instantly. This requires moving beyond "Request/Response" towards Bidirectional Communication.
1. WebSockets vs Polling
- Long Polling: Re-calling the API every 5 seconds. (Inefficient, "Choppy" feel).
- WebSockets: A permanent, open door between client and server. Data can be "Pushed" instantly. (Low latency, "Smooth" feel).
2. Optimistic UI Re-visited
In a real-time app, you must handle Race Conditions. What if User A and User B both edit the same name? You update optimistically, but if the server rejects because of a conflict, you must gracefully "Rollback" and notify the user. Tools like **React Query** or **RTK Query** provide the hooks to handle this complex logic.
4. Interview Mastery
Q: "When is SSE (Server-Sent Events) better than WebSockets?"
Architect Answer: "SSE is superior when communication is **One-way** (Server to Client). For example, a Facebook notification feed or a stock price ticker. SSE is lighter, works over standard HTTP, and has **Automatic Reconnection** built-in by the browser. WebSockets should be reserved for **Two-way** interactive experiences like a Chat app or a Collaborative Whiteboard."