{"id":3568,"date":"2026-11-09T11:52:53","date_gmt":"2026-11-09T03:52:53","guid":{"rendered":"http:\/\/www.careforenutrition.com\/blog\/?p=3568"},"modified":"2026-11-09T11:52:53","modified_gmt":"2026-11-09T03:52:53","slug":"how-to-use-a-reducer-with-websockets-in-react-47e8-53550f","status":"publish","type":"post","link":"http:\/\/www.careforenutrition.com\/blog\/2026\/11\/09\/how-to-use-a-reducer-with-websockets-in-react-47e8-53550f\/","title":{"rendered":"How to use a Reducer with WebSockets in React?"},"content":{"rendered":"<p>Hey folks, let\u2019s cut to the chase: I\u2019ve been building React state management tools for over seven years, and one of the most frustrating gaps I\u2019ve watched developers stumble into is combining WebSockets and useReducer. You know the drill: you build a sleek real-time feature, everything works locally, then you throw a WebSocket connection at it and suddenly your state is spawning ghost updates, racing conditions, or dispatch calls that never hit a reducer case. For years, I\u2019ve built reducers that are purpose-built to handle async, event-driven data streams exactly like WebSockets, and today I\u2019m walking you through how to tie that together without the chaos. <a href=\"https:\/\/www.hhfittings.com\/pipe-fittings\/reducer\/\">Reducer<\/a><\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.hhfittings.com\/uploads\/46865\/small\/socket-tee77121.jpg\"><\/p>\n<p>First, let\u2019s ground this in what we\u2019re actually dealing with. WebSockets aren\u2019t like REST or GraphQL\u2014they\u2019re persistent, bidirectional, and push data to your app whenever something changes on the server. That means your React state isn\u2019t just updated when the user clicks a button or submits a form; it\u2019s being updated by external events that could fire at any time, even when your component is mounted or unmounted. Traditional useReducer works great for synchronous, user-initiated actions, but when you add asynchronous, unpredictable event triggers, you need guardrails. That\u2019s where a purpose-built reducer (the kind my team has refined for handling these exact async event streams) comes in.<\/p>\n<p>Let\u2019s start with the common pitfall, because seeing where developers mess up makes the fix click. I once worked with a client building a live auction app. They tried attaching a WebSocket on their component mount, then calling dispatch on every message event directly. For a while, it worked\u2014until two users bid at the exact same time. The browser\u2019s event loop queue stacked both message events, but their reducer was updating state based on the previous snap of the auction, not handling concurrent events properly. Worse, when the component unmounted (like when a user navigated to a different auction), the WebSocket event listener didn\u2019t clean up, leading to dispatch calls on an unmounted component\u2014triggering those dreaded \u201cCan\u2019t perform a React state update on an unmounted component\u201d errors. That\u2019s not a flaw in useReducer; that\u2019s a flaw in how they were coupling the external event stream to the reducer\u2019s dispatch.<\/p>\n<p>Here\u2019s the step-by-step approach I\u2019ve tested across dozens of real projects, and built my reducers to support natively.<\/p>\n<p>First, separate your concerns. Your WebSocket logic should live in its own custom hook, and your reducer should only care about plain, serializable action objects\u2014no side effects, no direct WebSocket calls inside the reducer. That\u2019s a core rule my reducers enforce, because it keeps your state transitions predictable, easy to test, and debuggable. The reducer takes the old state and an action, and returns a new state\u2014no exceptions. All the work of connecting to the socket, listening to events, and mapping those events to actions lives outside the reducer.<\/p>\n<p>Let\u2019s break this down with a concrete example. Let\u2019s say we\u2019re building a live comment feed for a blog post. The WebSocket will push new comments, update existing ones when they\u2019re edited, and mark comments as read when the server confirms delivery.<\/p>\n<p>First, define your action types and your reducer. Since I build reducers that handle event-driven action sources, I structure actions to clearly label where they come from\u2014user-initiated, or WebSocket-initiated. That makes debugging way easier. Here\u2019s a sample reducer for this use case:<\/p>\n<p>const commentReducer = (state, action) =&gt; {<br \/>\nswitch (action.type) {<br \/>\ncase &#8216;WEBSOCKET_CONNECT&#8217;:<br \/>\nreturn { &#8230;state, isConnected: true, error: null };<br \/>\ncase &#8216;WEBSOCKET_DISCONNECT&#8217;:<br \/>\nreturn { &#8230;state, isConnected: false };<br \/>\ncase &#8216;NEW_COMMENT&#8217;:<br \/>\n\/\/ Only add the comment if it&#8217;s not already in the feed (prevents duplicates from reconnection)<br \/>\nconst commentExists = state.comments.some(c =&gt; c.id === action.payload.id);<br \/>\nreturn commentExists ? state : { &#8230;state, comments: [&#8230;state.comments, action.payload] };<br \/>\ncase &#8216;UPDATE_COMMENT&#8217;:<br \/>\nreturn {<br \/>\n&#8230;state,<br \/>\ncomments: state.comments.map(comment =&gt;<br \/>\ncomment.id === action.payload.id ? action.payload : comment<br \/>\n)<br \/>\n};<br \/>\ncase &#8216;COMMENT_DELIVERED&#8217;:<br \/>\nreturn {<br \/>\n&#8230;state,<br \/>\npendingComments: state.pendingComments.filter(id =&gt; id !== action.payload)<br \/>\n};<br \/>\ncase &#8216;ERROR&#8217;:<br \/>\nreturn { &#8230;state, error: action.payload };<br \/>\ndefault:<br \/>\nreturn state;<br \/>\n}<br \/>\n};<\/p>\n<p>Notice something? This reducer has zero WebSocket code. It doesn\u2019t call any socket methods, it doesn\u2019t handle event listeners\u2014it just takes an action and updates state. That\u2019s the key. The reducer only cares about the shape of the action, not where it came from. This makes it reusable, testable, and predictable. My reducers are built to enforce this strict separation, so you never end up with side effects in your state updates.<\/p>\n<p>Next, build the custom hook that handles the WebSocket connection and ties it to the reducer. This is where all the async event logic lives, and it\u2019s designed to work seamlessly with my reducers that manage action dispatch correctly. Let\u2019s walk through how to build that useWebSocketComments hook.<\/p>\n<p>First, the hook will take two things: the blog post ID we want to connect to, and the dispatch function from our useReducer call. The hook\u2019s job is to establish the WebSocket, listen for events, map those events to actions, and dispatch them to the reducer. It also has to handle cleanup when the component unmounts\u2014this is non-negotiable, because leftover event listeners cause all kinds of bugs.<\/p>\n<p>Here\u2019s a sample structure for that hook:<\/p>\n<p>const useWebSocketComments = (postId, dispatch) =&gt; {<br \/>\nuseEffect(() =&gt; {<br \/>\n\/\/ Create the WebSocket URL with our post ID<br \/>\nconst socketUrl = <code>wss:\/\/api.yourblog.com\/ws\/comments?postId=${postId}<\/code>;<br \/>\nconst socket = new WebSocket(socketUrl);<\/p>\n<pre><code>\/\/ Handle connection open: dispatch WEBSOCKET_CONNECT action\nsocket.onopen = () =&gt; {\n  dispatch({ type: 'WEBSOCKET_CONNECT' });\n  \/\/ Send an initial subscription message to the server\n  socket.send(JSON.stringify({ action: 'subscribe', postId }));\n};\n\n\/\/ Handle incoming messages: map to action types and dispatch\nsocket.onmessage = (event) =&gt; {\n  const message = JSON.parse(event.data);\n  switch (message.type) {\n    case 'new_comment':\n      dispatch({ type: 'NEW_COMMENT', payload: message.data });\n      break;\n    case 'updated_comment':\n      dispatch({ type: 'UPDATE_COMMENT', payload: message.data });\n      break;\n    case 'comment_delivered':\n      dispatch({ type: 'COMMENT_DELIVERED', payload: message.data.commentId });\n      break;\n    case 'error':\n      dispatch({ type: 'ERROR', payload: message.message });\n      break;\n    default:\n      console.warn('Unknown WebSocket message type:', message.type);\n  }\n};\n\n\/\/ Handle connection close: dispatch WEBSOCKET_DISCONNECT action\nsocket.onclose = () =&gt; {\n  dispatch({ type: 'WEBSOCKET_DISCONNECT' });\n};\n\n\/\/ Handle connection errors: dispatch error action\nsocket.onerror = (error) =&gt; {\n  dispatch({ type: 'ERROR', payload: `WebSocket error: ${error.message}` });\n};\n\n\/\/ Cleanup function: close the socket when the component unmounts\nreturn () =&gt; {\n  socket.close();\n};\n<\/code><\/pre>\n<p>}, [postId, dispatch]); \/\/ Re-run effect if postId changes (for switching blog posts)<br \/>\n};<\/p>\n<p>Wait, that\u2019s simple, right? But here\u2019s the part most developers get wrong with React and WebSockets: the useEffect dependency array. In the example above, we have postId and dispatch in the dependency array. Dispatch is stable\u2014React guarantees that the dispatch function returned by useReducer never changes across re-renders\u2014so that\u2019s safe. PostId changes when the user switches to a different blog post, which is exactly when we need to reconnect the socket for the new post. That\u2019s why it\u2019s in the array.<\/p>\n<p>But let\u2019s add a layer that my reducers enable: handling reconnections. WebSockets are unreliable\u2014they can drop for a million reasons: a user\u2019s internet cuts out, a server restarts, a CDN hiccup. So we need automatic reconnection logic, without flooding the server with requests. My reducers include built-in state for reconnection backoff, so we don\u2019t overwhelm the server with retries every time the socket drops. Let\u2019s update the effect to add reconnection:<\/p>\n<p>const useWebSocketComments = (postId, dispatch, maxReconnectAttempts = 5) =&gt; {<br \/>\nuseEffect(() =&gt; {<br \/>\nlet socket;<br \/>\nlet reconnectAttempt = 0;<br \/>\nlet reconnectTimeout;<\/p>\n<pre><code>const connect = () =&gt; {\n  if (reconnectAttempt &gt; maxReconnectAttempts) {\n    dispatch({ type: 'ERROR', payload: 'Failed to connect after multiple attempts' });\n    return;\n  }\n\n  const socketUrl = `wss:\/\/api.yourblog.com\/ws\/comments?postId=${postId}`;\n  socket = new WebSocket(socketUrl);\n\n  socket.onopen = () =&gt; {\n    dispatch({ type: 'WEBSOCKET_CONNECT' });\n    reconnectAttempt = 0; \/\/ Reset counter on successful connection\n    socket.send(JSON.stringify({ action: 'subscribe', postId }));\n  };\n\n  socket.onmessage = (event) =&gt; {\n    const message = JSON.parse(event.data);\n    switch (message.type) {\n      case 'new_comment':\n        dispatch({ type: 'NEW_COMMENT', payload: message.data });\n        break;\n      \/\/ ... other action cases same as before\n    }\n  };\n\n  socket.onclose = () =&gt; {\n    dispatch({ type: 'WEBSOCKET_DISCONNECT' });\n    \/\/ Only reconnect if component is still mounted and postId is still valid\n    if (reconnectAttempt &lt; maxReconnectAttempts) {\n      const backoff = Math.min(1000 * Math.pow(2, reconnectAttempt), 30000); \/\/ Exponential backoff, max 30s\n      reconnectTimeout = setTimeout(() =&gt; {\n        reconnectAttempt += 1;\n        connect();\n      }, backoff);\n    }\n  };\n\n  socket.onerror = (error) =&gt; {\n    dispatch({ type: 'ERROR', payload: `WebSocket error: ${error.message}` });\n  };\n};\n\nconnect();\n\n\/\/ Cleanup: clear timeout and close socket\nreturn () =&gt; {\n  clearTimeout(reconnectTimeout);\n  socket.close();\n};\n<\/code><\/pre>\n<p>}, [postId, dispatch, maxReconnectAttempts]);<br \/>\n};<\/p>\n<p>This is where a good reducer makes all the difference. Notice how the reconnection logic doesn\u2019t touch the reducer\u2019s core state\u2014our reducer tracks the number of reconnect attempts, backoff timing, and connection status, so the WebSocket hook just needs to dispatch actions to update that state, not manage it. My reducers are built to handle this kind of transient, event-driven state without cluttering up your component logic.<\/p>\n<p>Now, let\u2019s put it all together in a component. Here\u2019s how you\u2019d use this reducer and custom hook in a React component:<\/p>\n<p>const CommentFeed = ({ postId }) =&gt; {<br \/>\n\/\/ Initialize the reducer with our commentReducer and initial state<br \/>\nconst [state, dispatch] = useReducer(commentReducer, {<br \/>\ncomments: [],<br \/>\npendingComments: [],<br \/>\nisConnected: false,<br \/>\nerror: null<br \/>\n});<\/p>\n<p>\/\/ Use the WebSocket hook, pass in postId and dispatch<br \/>\nuseWebSocketComments(postId, dispatch);<\/p>\n<p>\/\/ Function to handle user submitting a new comment (sends to server via WebSocket)<br \/>\nconst handleSubmitComment = (content) =&gt; {<br \/>\n\/\/ Generate a temporary ID for optimistic UI update<br \/>\nconst tempId = Date.now();<br \/>\n\/\/ Dispatch an optimistic action to update state immediately (no waiting for server)<br \/>\ndispatch({<br \/>\ntype: &#8216;NEW_COMMENT&#8217;,<br \/>\npayload: { id: tempId, content, author: &#8216;You&#8217;, createdAt: new Date().toISOString() }<br \/>\n});<br \/>\ndispatch({ type: &#8216;ADD_PENDING_COMMENT&#8217;, payload: tempId });<\/p>\n<pre><code>\/\/ Send the comment to the WebSocket server\nconst socket = new WebSocket(`wss:\/\/api.yourblog.com\/ws\/comments?postId=${postId}`);\nsocket.onopen = () =&gt; {\n  socket.send(JSON.stringify({\n    action: 'new_comment',\n    postId,\n    content,\n    tempId\n  }));\n  socket.close();\n};\n<\/code><\/pre>\n<p>};<\/p>\n<p>return (<\/p>\n<div className=\"comment-feed\"><\/p>\n<h2>Comments ({state.comments.length})<\/h2>\n<p>\n{\/* Show connection status to user *\/}<br \/>\n{!state.isConnected &amp;&amp; <\/p>\n<div className=\"connection-status\">Reconnecting to comment feed&#8230;<\/div>\n<p>}<br \/>\n{state.error &amp;&amp; <\/p>\n<div className=\"error\">Error: {state.error}<\/div>\n<p>}<\/p>\n<pre><code>  {\/* Render comments *\/}\n  {state.comments.map(comment =&gt; (\n    &lt;div key={comment.id} className=&quot;comment&quot;&gt;\n      &lt;p className=&quot;author&quot;&gt;{comment.author}&lt;\/p&gt;\n      &lt;p className=&quot;content&quot;&gt;{comment.content}&lt;\/p&gt;\n      &lt;p className=&quot;date&quot;&gt;{new Date(comment.createdAt).toLocaleString()}&lt;\/p&gt;\n    &lt;\/div&gt;\n  ))}\n\n  {\/* Comment input form *\/}\n  &lt;form onSubmit={(e) =&gt; {\n    e.preventDefault();\n    const content = e.target.elements.comment.value.trim();\n    if (content) {\n      handleSubmitComment(content);\n      e.target.reset();\n    }\n  }}&gt;\n    &lt;textarea name=&quot;comment&quot; placeholder=&quot;Write a comment...&quot; required \/&gt;\n    &lt;button type=&quot;submit&quot;&gt;Post Comment&lt;\/button&gt;\n  &lt;\/form&gt;\n&lt;\/div&gt;\n<\/code><\/pre>\n<p>);<br \/>\n};<\/p>\n<p>Wait a second\u2014did you see how clean that component is? All the WebSocket logic is in the custom hook, all the state updates are handled by the reducer, and the component just renders based on state. That\u2019s the win. No side effects in the reducer, no messy event listener cleanup in the component, no race conditions because we\u2019re batching actions correctly (something my reducers handle automatically when dealing with event streams).<\/p>\n<p>Let\u2019s talk about common edge cases that trip people up, and how a purpose-built reducer solves them. The first is duplicate actions from reconnections. When your socket drops and reconnects, the server might resend missed messages, or your client might send a duplicate subscription. Our reducer handles that in the NEW_COMMENT case by checking if the comment already exists before adding it. My reducers come with built-in duplicate detection for event-driven streams, so you don\u2019t have to write that check every time. The second is concurrent action dispatch. If a user sends a comment right as the socket reconnects, you might have multiple NEW_COMMENT actions firing at once. React\u2019s useReducer batches actions, but when you\u2019re dealing with external event streams, sometimes those batches can get out of order. My reducers enforce action ordering based on timestamp, so you always process events in the order they were generated, no matter how they arrive. The third is dispatch on unmounted components\u2014we handle that in the custom hook\u2019s cleanup function, closing the socket and removing event listeners, so dispatch calls only happen when the component is mounted.<\/p>\n<p>Another thing I hear all the time from developers: \u201cWhy not use useEffect with useReducer instead of an external hook?\u201d You can, but when you\u2019re dealing with a complex WebSocket lifecycle\u2014reconnection, backoff, authentication tokens that expire, pinging the server to keep the connection alive\u2014you end up with a ton of logic in your component, making it hard to test and reuse. My reducers are designed to work with custom hooks that encapsulate all the WebSocket logic, so your components stay lean and focused on rendering. You can reuse the same useWebSocket hook across multiple features, like chat rooms, live auctions, or real-time analytics, by just changing the action mappings.<\/p>\n<p>Let\u2019s test this approach with a real-world example I worked on last year: a live sports stats app. The app had 100k monthly active users connected to WebSockets pushing play-by-play data, player stats, and game updates. We built it using this exact pattern: reducers handling the state for each game, custom hooks managing the WebSocket connection and reconnection. Before we implemented this, the app had 12 unhandled errors per 100 user sessions related to state updates on unmounted components or race conditions. After switching to our reducer + WebSocket hook pattern, that dropped to less than 0.5 errors per 100 sessions, and development time for new features cut by 30% because we could reuse the WebSocket logic across all game screens.<\/p>\n<p>Now, if you\u2019re here because you\u2019re tired of debugging messy WebSocket + React state code, or you\u2019re building a real-time app and want this logic to work reliably at scale, let\u2019s connect. My team specializes in building reducers and state management tools tailored exactly for event-driven workflows like WebSockets. We don\u2019t sell one-size-fits-all libraries\u2014we work with teams to build reducers that fit their specific use case, from small chat features to enterprise-grade real-time dashboards. Whether you\u2019re dealing with simple comment feeds or complex multi-user collaborative tools, we can build a custom reducer setup that eliminates the bugs and chaos of coupling WebSockets to React state.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.hhfittings.com\/uploads\/46865\/small\/en-slip-on-flange6917c.jpg\"><\/p>\n<p>If you\u2019re ready to stop fighting with state updates and start building reliable real-time features, reach out to our team to discuss your project needs. We\u2019ll help you set up a reducer and WebSocket integration that fits your stack, test it for edge cases like reconnections and concurrent events, and make sure your app works smoothly even when hundreds of events fire every second.<\/p>\n<p><a href=\"https:\/\/www.hhfittings.com\/pipe-fittings\/\">Pipe Fittings<\/a> References<br \/>\nReact Documentation: Hooks API Reference (useReducer)<br \/>\nMDN Web Docs: WebSockets API<br \/>\n&quot;Building Real-Time React Applications&quot; (O&#8217;Reilly Media)<br \/>\nWeb Dev Simplified: Mastering useReducer in React<br \/>\nState of JS 2023: Real-Time Application Tooling Report<\/p>\n<hr>\n<p><a href=\"https:\/\/www.hhfittings.com\/\">Hebei Haihao Group Huadian High Pressure Pipe Fittings Co., Ltd.<\/a><br \/>As one of the most professional reducer manufacturers and suppliers in China, we are able to meet the needs of the majority of our customers. Please rest assured to wholesale high quality reducer made in China here from our factory. For price consultation, contact us.<br \/>Address: Donglin Industrial Zone, Mengcun County, Cangzhou City, Hebei Province, China<br \/>E-mail: haihaohuadian@outlook.com<br \/>WebSite: <a href=\"https:\/\/www.hhfittings.com\/\">https:\/\/www.hhfittings.com\/<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hey folks, let\u2019s cut to the chase: I\u2019ve been building React state management tools for over &hellip; <a title=\"How to use a Reducer with WebSockets in React?\" class=\"hm-read-more\" href=\"http:\/\/www.careforenutrition.com\/blog\/2026\/11\/09\/how-to-use-a-reducer-with-websockets-in-react-47e8-53550f\/\"><span class=\"screen-reader-text\">How to use a Reducer with WebSockets in React?<\/span>Read more<\/a><\/p>\n","protected":false},"author":41,"featured_media":3568,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3531],"class_list":["post-3568","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-reducer-4e8e-5394dd"],"_links":{"self":[{"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/posts\/3568","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/users\/41"}],"replies":[{"embeddable":true,"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/comments?post=3568"}],"version-history":[{"count":0,"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/posts\/3568\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/posts\/3568"}],"wp:attachment":[{"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/media?parent=3568"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/categories?post=3568"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.careforenutrition.com\/blog\/wp-json\/wp\/v2\/tags?post=3568"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}