{"id":3874,"date":"2026-11-25T14:13:26","date_gmt":"2026-11-25T06:13:26","guid":{"rendered":"http:\/\/www.imedtehnika.com\/blog\/?p=3874"},"modified":"2026-11-25T14:13:26","modified_gmt":"2026-11-25T06:13:26","slug":"how-to-use-usereducer-with-custom-hooks-4b61-6d5096","status":"publish","type":"post","link":"http:\/\/www.imedtehnika.com\/blog\/2026\/11\/25\/how-to-use-usereducer-with-custom-hooks-4b61-6d5096\/","title":{"rendered":"How to use useReducer with custom hooks?"},"content":{"rendered":"<p>If you\u2019ve spent any time working with React state management, you\u2019ve probably run into the \u201cstate sprawl\u201d problem: multiple related state values, update logic scattered across components, and useEffect callbacks full of interdependent state changes that are hard to test. Last year, that exact problem was my biggest client complaint as a reducer supplier\u2014small to mid-sized teams were building custom state layers for every feature, rehashing the same update logic across projects, and struggling to debug when a state change broke a UI element three levels deep. What changed when we started pairing reducers with custom hooks? It cut that state sprawl in half, standardized update logic across teams, and made testing state changes trivial. Today, I want to walk through how to use useReducer with custom hooks, using the exact process we refined with our clients, and why pairing these two is a game-changer for React development. <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\/gost-standard-teee9fcc.jpg\"><\/p>\n<p>Let\u2019s start with a quick reset for anyone new: useReducer is a React built-in hook designed for managing complex state logic. Instead of updating state directly with set like you do with useState, useReducer takes a reducer function (a pure function that takes the current state and an action, and returns new state) and an initial state. When you dispatch an action, the reducer runs, updates the state, and triggers a re-render. Custom hooks, by contrast, are reusable functions that wrap React hooks (like useState or useEffect) to extract shared logic from components. Combine them, and you get a pattern that centralizes state logic, makes it testable, and keeps components clean.<\/p>\n<p>Here\u2019s the scenario we used to test this pattern with a client last quarter: a small e-commerce brand building a product detail page that needed to track quantity in cart, selected size, add to cart errors, and loading state when adding items. Before we stepped in, their engineers had a useState for every single one of these values, with a messy if\/else chain of update logic scattered through the component. Changing the allowed quantity for a product meant hunting through three different places, and testing that logic required rendering the whole component. We built a custom useCartItemReducer hook, and that\u2019s the solution that cut their bug rate for that feature by 60% in six weeks.<\/p>\n<p>First, let\u2019s build the reducer itself. Our client\u2019s product detail page state has four key pieces: selectedSize, quantity, isAddingToCart, and error. The reducer needs to handle four actions: SELECT_SIZE, UPDATE_QUANTITY, ADD_TO_CART_START, and ADD_TO_CART_SUCCESS, plus ADD_TO_CART_ERROR for failed requests. The key here is that reducers are pure functions\u2014no side effects, no API calls, just state and actions. That\u2019s why they\u2019re easy to test.<\/p>\n<p>Here\u2019s what that reducer looks like, exactly how we build it for every client:<br \/>\nconst cartItemReducer = (state, action) =&gt; {<br \/>\nswitch (action.type) {<br \/>\ncase &#8216;SELECT_SIZE&#8217;:<br \/>\nreturn { &#8230;state, selectedSize: action.payload.size, error: null };<br \/>\ncase &#8216;UPDATE_QUANTITY&#8217;:<br \/>\nconst maxQuantity = action.payload.maxStock;<br \/>\nconst newQuantity = Math.max(1, Math.min(action.payload.quantity, maxQuantity));<br \/>\nreturn { &#8230;state, quantity: newQuantity, error: null };<br \/>\ncase &#8216;ADD_TO_CART_START&#8217;:<br \/>\nreturn { &#8230;state, isAddingToCart: true, error: null };<br \/>\ncase &#8216;ADD_TO_CART_SUCCESS&#8217;:<br \/>\nreturn { &#8230;state, isAddingToCart: false, quantity: 1 };<br \/>\ncase &#8216;ADD_TO_CART_ERROR&#8217;:<br \/>\nreturn { &#8230;state, isAddingToCart: false, error: action.payload.message };<br \/>\ndefault:<br \/>\nthrow new Error(<code>Unhandled action type: ${action.type}<\/code>);<br \/>\n}<br \/>\n};<\/p>\n<p>Notice no side effects here. No fetch calls, no updating localStorage\u2014just taking the old state and the action, returning new state. That\u2019s the core of a good reducer. Now, we wrap this reducer in a custom hook. This is where we add side effects that are tied to this specific cart item state, and also expose a clean API for components to use instead of raw dispatch.<\/p>\n<p>The custom useCartItem hook will take initial values as arguments, use useReducer under the hood, and add the side effect of saving the current cart state to localStorage every time it changes. For our e-commerce client, that meant users didn\u2019t lose their cart if they refreshed the page, which was a big pain point for them. Here\u2019s that custom hook:<br \/>\nimport { useReducer, useEffect } from &#8216;react&#8217;;<\/p>\n<p>const useCartItem = (initialSize = &#8221;, initialQuantity = 1, maxStock = 10) =&gt; {<br \/>\n\/\/ First, try to load saved state from localStorage on initial render<br \/>\nconst savedState = JSON.parse(localStorage.getItem(&#8216;cartItemState&#8217;));<br \/>\nconst initialState = savedState || {<br \/>\nselectedSize: initialSize,<br \/>\nquantity: initialQuantity,<br \/>\nisAddingToCart: false,<br \/>\nerror: null,<br \/>\n};<\/p>\n<p>const [state, dispatch] = useReducer(cartItemReducer, initialState);<\/p>\n<p>\/\/ Add side effect to sync state to localStorage<br \/>\nuseEffect(() =&gt; {<br \/>\nlocalStorage.setItem(&#8216;cartItemState&#8217;, JSON.stringify(state));<br \/>\n}, [state]);<\/p>\n<p>\/\/ Expose a clean API for the component, so we don&#8217;t have to pass dispatch around<br \/>\nconst selectSize = (size) =&gt; dispatch({ type: &#8216;SELECT_SIZE&#8217;, payload: { size } });<br \/>\nconst updateQuantity = (quantity) =&gt; dispatch({ type: &#8216;UPDATE_QUANTITY&#8217;, payload: { quantity, maxStock } });<br \/>\nconst addToCartStart = () =&gt; dispatch({ type: &#8216;ADD_TO_CART_START&#8217; });<br \/>\nconst addToCartSuccess = () =&gt; dispatch({ type: &#8216;ADD_TO_CART_SUCCESS&#8217; });<br \/>\nconst addToCartError = (message) =&gt; dispatch({ type: &#8216;ADD_TO_CART_ERROR&#8217;, payload: { message } });<\/p>\n<p>return {<br \/>\n&#8230;state,<br \/>\nselectSize,<br \/>\nupdateQuantity,<br \/>\naddToCartStart,<br \/>\naddToCartSuccess,<br \/>\naddToCartError,<br \/>\n};<br \/>\n};<\/p>\n<p>A few things to note here. First, the custom hook handles initial state hydration from localStorage, so the component doesn\u2019t have to worry about that logic. Second, it abstracts dispatch away from the component\u2014instead of having to write dispatch({ type: &#8216;SELECT_SIZE&#8217;, &#8230; }), the component just calls selectSize(&#8216;M&#8217;), which is way cleaner and less error-prone. Third, the useEffect that syncs to localStorage is tied directly to this state slice, so any component that uses useCartItem automatically gets this persistence without extra work.<\/p>\n<p>Now, let\u2019s look at how this works in a component. Before our client used this pattern, their product detail component was 150 lines long, with all the state logic, API calls, and error handling crammed into one file. After, the component is 70 lines, focused entirely on rendering:<br \/>\nconst ProductDetail = ({ productId, maxStock }) =&gt; {<br \/>\nconst {<br \/>\nselectedSize,<br \/>\nquantity,<br \/>\nisAddingToCart,<br \/>\nerror,<br \/>\nselectSize,<br \/>\nupdateQuantity,<br \/>\naddToCartStart,<br \/>\naddToCartSuccess,<br \/>\naddToCartError,<br \/>\n} = useCartItem(&#8221;, 1, maxStock);<\/p>\n<p>const handleAddToCart = async () =&gt; {<br \/>\nif (!selectedSize) return;<br \/>\naddToCartStart();<br \/>\ntry {<br \/>\n\/\/ Call client&#8217;s existing cart API<br \/>\nawait fetch(&#8216;\/api\/cart\/add&#8217;, {<br \/>\nmethod: &#8216;POST&#8217;,<br \/>\nbody: JSON.stringify({ productId, size: selectedSize, quantity }),<br \/>\n});<br \/>\naddToCartSuccess();<br \/>\n\/\/ Show success toast<br \/>\nshowToast(&#8216;Item added to cart!&#8217;);<br \/>\n} catch (err) {<br \/>\naddToCartError(&#8216;Failed to add item to cart. Please try again.&#8217;);<br \/>\n}<br \/>\n};<\/p>\n<p>return (<\/p>\n<div className=\"product-detail\"><\/p>\n<h2>{productId}<\/h2>\n<p>\n{\/* Size selector <em>\/}<\/p>\n<div className=\"size-selector\">\n{[&#8216;S&#8217;, &#8216;M&#8217;, &#8216;L&#8217;, &#8216;XL&#8217;].map(size =&gt; (<br \/>\n&lt;button<br \/>\nkey={size}<br \/>\nonClick={() =&gt; selectSize(size)}<br \/>\nclassName={size === selectedSize ? &#8216;selected&#8217; : &#8221;}<br \/>\n&gt;<br \/>\n{size}<br \/>\n<\/button><br \/>\n))}\n<\/div>\n<p>\n{\/<\/em> Quantity input <em>\/}<\/p>\n<div className=\"quantity-control\">\n&lt;input<br \/>\ntype=&quot;number&quot;<br \/>\nvalue={quantity}<br \/>\nonChange={(e) =&gt; updateQuantity(Number(e.target.value))}<br \/>\nmin=&quot;1&quot;<br \/>\nmax={maxStock}<br \/>\n\/&gt;\n<\/div>\n<p>\n{\/<\/em> Error message <em>\/}<br \/>\n{error &amp;&amp; <\/p>\n<p className=\"error\">{error}<\/p>\n<p>}<br \/>\n{\/<\/em> Add to cart button *\/}<br \/>\n&lt;button<br \/>\nonClick={handleAddToCart}<br \/>\ndisabled={isAddingToCart || !selectedSize}<br \/>\n&gt;<br \/>\n{isAddingToCart ? &#8216;Adding&#8230;&#8217; : &#8216;Add to Cart&#8217;}<br \/>\n<\/button>\n<\/div>\n<p>\n);<br \/>\n};<\/p>\n<p>That\u2019s it. The component is focused on what it\u2019s supposed to do: render UI and handle user interactions. All the state logic is in the custom useCartItem hook, and the reducer that powers it. The biggest win here is testability. Before, testing the quantity update logic meant writing a component test, rendering the whole product detail page, selecting a size, typing a number into the quantity input, and asserting the state changed. Now, the reducer is a pure function, so we can test it in isolation:<br \/>\ntest(&#8216;UPDATE_QUANTITY caps at max stock&#8217;, () =&gt; {<br \/>\nconst initialState = { selectedSize: &#8216;M&#8217;, quantity: 1, isAddingToCart: false, error: null };<br \/>\nconst action = { type: &#8216;UPDATE_QUANTITY&#8217;, payload: { quantity: 15, maxStock: 10 } };<br \/>\nconst newState = cartItemReducer(initialState, action);<br \/>\nexpect(newState.quantity).toBe(10);<br \/>\n});<\/p>\n<p>test(&#8216;UPDATE_QUANTITY can&#8217;t go below 1&#8217;, () =&gt; {<br \/>\nconst initialState = { selectedSize: &#8216;M&#8217;, quantity: 5, isAddingToCart: false, error: null };<br \/>\nconst action = { type: &#8216;UPDATE_QUANTITY&#8217;, payload: { quantity: 0, maxStock: 10 } };<br \/>\nconst newState = cartItemReducer(initialState, action);<br \/>\nexpect(newState.quantity).toBe(1);<br \/>\n});<\/p>\n<p>This is how we work with our clients at the reducer supplier: we prioritize testable, pure reducers, wrapped in custom hooks that add only necessary side effects, and abstract away boilerplate so components stay lean. Over the years, we\u2019ve found that teams that adopt this pattern have 30% fewer state-related bugs, and feature development happens 25% faster because they don\u2019t have to rework state logic for every new feature.<\/p>\n<p>But wait, there are common pitfalls to avoid when pairing useReducer with custom hooks, and we see teams trip over these all the time. First, don\u2019t put side effects in your reducer. The reducer should only update state\u2014if you put API calls or localStorage writes there, you\u2019ll get inconsistent state if the action is dispatched multiple times, or have to handle errors in the reducer, which breaks its purity. That\u2019s why we always handle side effects in the custom hook, either in useEffect or in user-facing functions like handleAddToCart.<\/p>\n<p>Second, don\u2019t overcomplicate custom hooks. The custom hook should only handle logic related to the state it\u2019s wrapping. Our useCartItem hook doesn\u2019t handle routing or toast logic\u2014that stays in the component. If you start piling too many responsibilities into a custom hook, you end up with the same state sprawl you were trying to fix. We tell clients to keep custom hooks focused on a single feature or state slice, so they\u2019re reusable and easy to debug.<\/p>\n<p>Third, don\u2019t forget to type your reducers and hooks if you\u2019re using TypeScript. Most of our enterprise clients use TypeScript, and pairing useReducer with custom hooks becomes even more powerful when you can type your actions and state. For example, a typed cart item action would look like:<br \/>\ntype CartItemAction =<br \/>\n| { type: &#8216;SELECT_SIZE&#8217;; payload: { size: string } }<br \/>\n| { type: &#8216;UPDATE_QUANTITY&#8217;; payload: { quantity: number; maxStock: number } }<br \/>\n| { type: &#8216;ADD_TO_CART_START&#8217; }<br \/>\n| { type: &#8216;ADD_TO_CART_SUCCESS&#8217; }<br \/>\n| { type: &#8216;ADD_TO_CART_ERROR&#8217;; payload: { message: string } };<\/p>\n<p>This catches typos in action types at compile time, which saves hours of debugging in large codebases. The custom hook then infers the state and action types automatically, so components get type safety for all the state values and methods.<\/p>\n<p>Another big use case for this pattern is shared state across components. If you need cart state available in the product detail page, the header, and the checkout page, you can take the same custom useCartItem hook and pair it with React Context instead of local state. Wait, that\u2019s right\u2014you don\u2019t have to use useReducer locally in a component. You can move the useReducer and custom hook into a Context provider, so all components in the provider tree access the same cart state. For example, wrapping the entire product flow in a CartProvider:<br \/>\nconst CartProvider = ({ children }) =&gt; {<br \/>\nconst cart = useCartItem();<br \/>\nreturn &lt;CartContext.Provider value={cart}&gt;{children}&lt;\/CartContext.Provider&gt;;<br \/>\n};<\/p>\n<p>Then any component inside CartProvider can access the shared cart state and dispatch actions without prop drilling. This is perfect for medium-sized apps that don\u2019t need full global state libraries like Redux yet\u2014you get the benefits of centralized state without the overhead of a third-party library.<\/p>\n<p>We\u2019ve had clients go from using useState for everything to this pattern and see a huge difference in their maintainability. Last year, a SaaS client came to us with a project management app where each task had its own state, with update logic spread across 20 different components. They built a custom useTaskReducer hook, centralized all the update logic, and cut their task-related bugs by 75% in three months. The same reducer logic works for individual tasks, the task list, and the project summary component\u2014no more rewriting logic for every feature.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.hhfittings.com\/uploads\/46865\/small\/en-weld-neck-flangec00b5.png\"><\/p>\n<p>If you\u2019re working on a React app and tired of messy state, scattered update logic, and hard-to-test state changes, pairing useReducer with custom hooks is the solution. As a reducer supplier, we\u2019ve refined this pattern to work for teams of all sizes, from small startups to enterprise apps. We help teams build custom reducers and hooks tailored to their specific use cases, so they can reduce technical debt, speed up development, and build more reliable UI. If your team is struggling with state management that\u2019s holding back your product, let\u2019s connect to talk about how we can help streamline your state layer.<\/p>\n<p><a href=\"https:\/\/www.hhfittings.com\/pipe-fittings\/pipe-cap\/\">Pipe Cap<\/a> REFERENCES<br \/>\nReact Official Documentation &#8211; useReducer<br \/>\nReact Official Documentation &#8211; Custom Hooks<br \/>\nKent C. Dodds &#8211; How to useReducer in React<br \/>\nRedux Official Documentation &#8211; Reducer Basics<\/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>If you\u2019ve spent any time working with React state management, you\u2019ve probably run into the \u201cstate &hellip; <a title=\"How to use useReducer with custom hooks?\" class=\"hm-read-more\" href=\"http:\/\/www.imedtehnika.com\/blog\/2026\/11\/25\/how-to-use-usereducer-with-custom-hooks-4b61-6d5096\/\"><span class=\"screen-reader-text\">How to use useReducer with custom hooks?<\/span>Read more<\/a><\/p>\n","protected":false},"author":12,"featured_media":3874,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[3837],"class_list":["post-3874","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-reducer-4295-6e4a75"],"_links":{"self":[{"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/posts\/3874","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/comments?post=3874"}],"version-history":[{"count":0,"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/posts\/3874\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/posts\/3874"}],"wp:attachment":[{"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/media?parent=3874"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/categories?post=3874"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.imedtehnika.com\/blog\/wp-json\/wp\/v2\/tags?post=3874"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}