How do you handle real-time state updates with WebSockets and Redux?
Answer
Integrating WebSocket real-time updates with Redux: Middleware approach: create middleware that manages the WebSocket connection: const socketMiddleware = (store) => { const socket = new WebSocket(WS_URL); socket.onmessage = (event) => { const data = JSON.parse(event.data); store.dispatch(messageReceived(data)); }; return (next) => (action) => { if (action.type === "socket/send") socket.send(JSON.stringify(action.payload)); return next(action); }; }. RTK Query with WebSocket: use onCacheEntryAdded in endpoints to manage subscriptions: async onCacheEntryAdded(arg, { updateCachedData, cacheDataLoaded, cacheEntryRemoved }) { const ws = new WebSocket(...); ws.onmessage = (event) => updateCachedData((draft) => { draft.messages.push(JSON.parse(event.data)); }); await cacheEntryRemoved; ws.close(); }. Optimistic updates: immediately update state when sending, confirm on server acknowledgement, revert on error. Reconnection: implement exponential backoff reconnection in the middleware with status tracking in the Redux state. State synchronization: use sequence numbers or vector clocks for conflict detection when multiple clients modify the same state.
Previous
What are the patterns for sharing state between micro-frontends?
Next
What are the advanced patterns for selector composition?
More Redux / State Management Questions
View all →- Advanced How do you architect state management for large-scale React applications?
- Advanced What is Redux-Saga and how does it differ from Thunks?
- Advanced What is XState and state machines in UI development?
- Advanced How does TanStack Query's caching and staleness model work?
- Advanced What are the patterns for sharing state between micro-frontends?