{"id":879,"date":"2026-11-21T11:16:38","date_gmt":"2026-11-21T03:16:38","guid":{"rendered":"http:\/\/www.pixelmateindia.com\/blog\/?p=879"},"modified":"2026-11-21T11:16:38","modified_gmt":"2026-11-21T03:16:38","slug":"how-to-use-usereducer-in-react-4a6e-6bdf93","status":"publish","type":"post","link":"http:\/\/www.pixelmateindia.com\/blog\/2026\/11\/21\/how-to-use-usereducer-in-react-4a6e-6bdf93\/","title":{"rendered":"How to use useReducer in React?"},"content":{"rendered":"<p>If you\u2019ve spent any time building React apps, you\u2019ve probably run into the moment where state updates stop feeling straightforward. You might have a component with a dozen different state variables, each tied to a handler that updates it, and suddenly adding a new feature means chasing down three different functions to make sure nothing breaks. That\u2019s where I come in\u2014my company specializes in building, optimizing, and supporting reducers for teams that want to keep their React state predictable and maintainable. After years of working with developers across industries, I\u2019ve seen firsthand how many teams struggle to switch from <code>useState<\/code> to <code>useReducer, or how to use the hook well when they do. Today I\u2019m breaking down exactly how to use <\/code>useReducer` in React, and how custom reducers built by our team can make this tool work even better for your app. <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\/steel-pipe-elbowa18e6.jpg\"><\/p>\n<p>First, let\u2019s start with the basics: what is <code>useReducer<\/code> and when do you actually need it? Unlike <code>useState<\/code>, which lets you update state by directly setting a new value, <code>useReducer<\/code> uses a pattern called reducer state management. A reducer is a pure function that takes two inputs: the current state of your component, and an \u201caction\u201d that describes what change you want to make. It returns a new state, and that\u2019s it\u2014no side effects, no random changes, just a predictable transformation. The <code>useReducer<\/code> hook wraps this pattern, letting you access the current state and a <code>dispatch<\/code> function that you use to send actions to the reducer.<\/p>\n<p>A lot of developers default to <code>useState<\/code> for every component, and that works fine for small apps with just a few state variables. But when you\u2019re dealing with complex state: multiple sub-values (like a form with name, email, password, and error status), state that depends on previous values, or state updates that get repeated across components, <code>useReducer<\/code> becomes a game-changer. It centralizes all your state update logic in one place, making it easier to test, debug, and scale. Our team often sees teams waste hours trying to track down a weird state bug in a component with five separate <code>useState<\/code> calls\u2014when a reducer would have made that bug obvious in minutes.<\/p>\n<p>Let\u2019s walk through the core syntax to make this concrete. The basic structure of <code>useReducer<\/code> looks like this:<\/p>\n<p>First, you define your reducer function. For a simple example, let\u2019s say we\u2019re building a shopping cart. The state will be an array of items, and actions will be things like adding an item, removing an item, or updating the quantity.<\/p>\n<pre><code class=\"language-javascript\">function cartReducer(state, action) {\n  switch(action.type) {\n    case 'ADD_ITEM':\n      \/\/ Return a new array so React knows state has changed\n      return [...state, action.payload];\n    case 'REMOVE_ITEM':\n      return state.filter(item =&gt; item.id !== action.payload.id);\n    case 'UPDATE_QUANTITY':\n      return state.map(item =&gt; \n        item.id === action.payload.id \n          ? {...item, quantity: action.payload.quantity} \n          : item\n      );\n    default:\n      \/\/ If someone sends an unknown action, return the current state\n      return state;\n  }\n}\n<\/code><\/pre>\n<p>Notice that this reducer is a pure function: it never changes the original <code>state<\/code> array, it just returns a new one. That\u2019s a key rule of reducers\u2014if you mutate state directly, React won\u2019t re-render your component, and your state updates will be inconsistent.<\/p>\n<p>Next, you use the <code>useReducer<\/code> hook in your component. You pass the reducer function and an initial state, and the hook gives you the current state and the <code>dispatch<\/code> function.<\/p>\n<pre><code class=\"language-javascript\">import { useReducer } from 'react';\n\nfunction ShoppingCart() {\n  const [cart, dispatch] = useReducer(cartReducer, []);\n\n  \/\/ Handlers that dispatch actions\n  const addItem = (item) =&gt; {\n    dispatch({ type: 'ADD_ITEM', payload: item });\n  };\n\n  const removeItem = (item) =&gt; {\n    dispatch({ type: 'REMOVE_ITEM', payload: item });\n  };\n\n  const updateQuantity = (id, quantity) =&gt; {\n    dispatch({ type: 'UPDATE_QUANTITY', payload: { id, quantity } });\n  };\n\n  \/\/ ... rest of your component\n}\n<\/code><\/pre>\n<p>This is where the power becomes clear. Instead of having three separate handlers that each update state, you have one dispatch function that sends actions to a central reducer. If you need to add a new action\u2014like clearing the entire cart\u2014you just add a new case to your reducer, no need to rewrite handlers all over your component. For a small shopping cart, this might not feel like a huge difference, but for a component with 10 different state updates, this structure eliminates a lot of confusion.<\/p>\n<p>Now, let\u2019s talk about common pitfalls that new developers run into with <code>useReducer<\/code>, and how our team\u2019s approach to reducers avoids these issues. The first big mistake is making reducers too complex. A reducer should handle one domain of state\u2014our team builds reducers that are single-responsibility, so a cart reducer only handles cart state, a form reducer only handles form input, and so on. If you have a reducer that\u2019s 500 lines long and handles 10 different state types, it becomes just as hard to maintain as a dozen <code>useState<\/code> calls. Our custom reducers are modular, so you can combine them if needed, but each one stays focused.<\/p>\n<p>Another common pitfall is mutating state inside the reducer. Let\u2019s say someone writes their <code>REMOVE_ITEM<\/code> case like this:<\/p>\n<pre><code class=\"language-javascript\">case 'REMOVE_ITEM':\n  state.splice(state.findIndex(item =&gt; item.id === action.payload.id), 1);\n  return state;\n<\/code><\/pre>\n<p>This is wrong because <code>splice<\/code> mutates the original state array. React compares the previous state and new state by reference, so it won\u2019t notice that the array changed, and your component won\u2019t re-render. Even worse, mutation can lead to hard-to-debug side effects\u2014if another component is using the same cart state, you might accidentally change it without dispatching an action. Our team tests every reducer we build for immutability, so you never have to worry about these bugs.<\/p>\n<p>Then there\u2019s the issue of initial state. Sometimes developers set initial state directly in the <code>useReducer<\/code> call, but for more complex apps, you might need to compute initial state based on props or local storage. You can do that with a third argument to <code>useReducer<\/code>: the <code>init<\/code> function. For example, if you want to load saved cart items from local storage:<\/p>\n<pre><code class=\"language-javascript\">const init = (initialCart) =&gt; {\n  const savedCart = localStorage.getItem('cart');\n  return savedCart ? JSON.parse(savedCart) : initialCart;\n};\n\nconst [cart, dispatch] = useReducer(cartReducer, [], init);\n<\/code><\/pre>\n<p>This keeps your initial state logic separate from your reducer, which makes it easier to test and update. Our reducers include built-in init functions for common use cases like form state, user sessions, and cart state, so you don\u2019t have to write that logic from scratch.<\/p>\n<p>Let\u2019s also talk about when to use <code>useReducer<\/code> vs. <code>useState<\/code>. A good rule of thumb is: if you find yourself updating multiple related state variables in the same handler, or if state updates depend on complex logic (like calculating a total, or validating form inputs before updating), go with <code>useReducer<\/code>. If you\u2019re just toggling a modal or keeping track of a single input value, <code>useState<\/code> is still fine. But even for medium complexity, <code>useReducer<\/code> saves you time long-term. Our team often recommends switching to <code>useReducer<\/code> when your component has more than three state variables, because the structure makes it easy to add new features without refactoring everything.<\/p>\n<p>Another advanced feature of <code>useReducer<\/code> is being able to dispatch from other components. If you have a cart component and a product component, and you want the product component to dispatch an \u201cadd item\u201d action, you don\u2019t have to pass every handler down as props. You can create a context for the cart state and dispatch, so any component can access dispatch and send actions to the reducer. That pattern eliminates prop drilling, which is a huge pain point in React apps with nested components. Our team has pre-built context providers for reducers, so you can set up this pattern in minutes instead of hours.<\/p>\n<p>Now, let\u2019s talk about why our reducer services matter. A lot of developers can write a basic reducer, but building one that\u2019s optimized for performance, tested for edge cases, and integrates smoothly with other React tools takes experience. We\u2019ve built reducers for everything from e-commerce carts to form management systems to state for real-time dashboards, and we\u2019ve learned how to avoid common performance issues. For example, when using <code>useReducer<\/code> with large lists, you can memoize dispatch functions to prevent unnecessary re-renders, but that can get complicated. Our team builds reducers that include memoization out of the box, so your components only re-render when the state actually changes, even for large datasets.<\/p>\n<p>We also handle debugging, which is one of the biggest benefits of using a centralized reducer. When you have a bug in state, you can look at every action that was dispatched, every state update, and track exactly where things went wrong. This is a huge time-saver for developers, especially in large teams where multiple people are working on the same app. Our reducers include built-in action logging, so you can see every state change in your browser\u2019s dev tools, no extra code needed.<\/p>\n<p>Let\u2019s address a common objection: \u201cI heard Redux is better than <code>useReducer<\/code> for large apps.\u201d It\u2019s true that Redux is a full state management library, but <code>useReducer<\/code> is a built-in React hook, and for many apps, it\u2019s all you need. Redux adds extra boilerplate and complexity that you don\u2019t need for small to medium apps. Our company works with teams to decide when to use <code>useReducer<\/code> and when to move to Redux, and we build both reducers for <code>useReducer<\/code> and Redux slices if that\u2019s what you need. We don\u2019t push one solution over the other\u2014we build what works for your specific app.<\/p>\n<p>Another thing to note: when you\u2019re testing your components, reducers are super easy to test because they\u2019re pure functions. You can pass in a state and an action, and assert that the output is correct, no need to mount components or simulate events. Our team writes test cases for every reducer we build, so you can run those tests as part of your CI pipeline and be confident that your state updates work as expected. For example, you could write a test for your cart reducer:<\/p>\n<pre><code class=\"language-javascript\">test('adds an item to cart', () =&gt; {\n  const initialState = [];\n  const action = { type: 'ADD_ITEM', payload: { id: 1, name: 'T-Shirt', quantity: 1 } };\n  const newState = cartReducer(initialState, action);\n  expect(newState).toEqual([{ id: 1, name: 'T-Shirt', quantity: 1 }]);\n});\n<\/code><\/pre>\n<p>This test runs in milliseconds, and if you change your reducer later, you just update the test\u2014no messy component tests to rewrite. Our reducers come with pre-written test suites, so you don\u2019t have to build that from scratch either.<\/p>\n<p>Let\u2019s wrap this up with a real example of how <code>useReducer<\/code> works in a full component, and how our reducers make it simpler. Imagine a user profile form that has fields for name, email, password, and a error message for invalid inputs. Instead of four separate <code>useState<\/code> calls, you\u2019d use a form reducer:<\/p>\n<pre><code class=\"language-javascript\">import { useReducer } from 'react';\n\nconst initialFormState = {\n  name: '',\n  email: '',\n  password: '',\n  error: ''\n};\n\nfunction formReducer(state, action) {\n  switch(action.type) {\n    case 'UPDATE_FIELD':\n      return {...state, [action.field]: action.value, error: ''};\n    case 'SET_ERROR':\n      return {...state, error: action.message};\n    case 'RESET_FORM':\n      return initialFormState;\n    default:\n      return state;\n  }\n}\n\nfunction ProfileForm() {\n  const [formState, dispatch] = useReducer(formReducer, initialFormState);\n\n  const handleSubmit = (e) =&gt; {\n    e.preventDefault();\n    \/\/ Validate input before updating\n    if (!formState.email.includes('@')) {\n      dispatch({ type: 'SET_ERROR', message: 'Please enter a valid email' });\n      return;\n    }\n    \/\/ Submit form logic here\n  };\n\n  return (\n    &lt;form onSubmit={handleSubmit}&gt;\n      {formState.error &amp;&amp; &lt;div className=&quot;error&quot;&gt;{formState.error}&lt;\/div&gt;}\n      &lt;input\n        type=&quot;text&quot;\n        value={formState.name}\n        onChange={(e) =&gt; dispatch({ type: 'UPDATE_FIELD', field: 'name', value: e.target.value })}\n        placeholder=&quot;Name&quot;\n      \/&gt;\n      &lt;input\n        type=&quot;email&quot;\n        value={formState.email}\n        onChange={(e) =&gt; dispatch({ type: 'UPDATE_FIELD', field: 'email', value: e.target.value })}\n        placeholder=&quot;Email&quot;\n      \/&gt;\n      &lt;input\n        type=&quot;password&quot;\n        value={formState.password}\n        onChange={(e) =&gt; dispatch({ type: 'UPDATE_FIELD', field: 'password', value: e.target.value })}\n        placeholder=&quot;Password&quot;\n      \/&gt;\n      &lt;button type=&quot;submit&quot;&gt;Save Profile&lt;\/button&gt;\n    &lt;\/form&gt;\n  );\n}\n<\/code><\/pre>\n<p>This form is easy to extend\u2014if you add a new field like \u201cphone number\u201d, you just add a <code>field<\/code> case to the reducer, no new state variables. If you need to add validation for the phone number, you update the <code>handleSubmit<\/code> function. Our team builds form reducers that handle all this logic, including validation, error handling, and persistence, so you can drop a pre-built form reducer into your component instead of writing it yourself.<\/p>\n<p>So, when should you use <code>useReducer<\/code>? When your state logic gets complex, when you want predictable updates, when you need to test your state easily, or when you want to avoid prop drilling. And if you don\u2019t want to build reducers from scratch, our team is here to help. We work with teams of all sizes, from startups building their first React app to enterprise teams maintaining large codebases, to build custom reducers that fit their exact needs. We handle everything from basic reducers for small components to large, scaled state management systems for entire apps, so you can focus on building features instead of debugging state bugs.<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.hhfittings.com\/uploads\/46865\/small\/threaded-pipe-tee77bc3.jpg\"><\/p>\n<p>If you\u2019re tired of messy state updates, hard-to-track bugs, and spending hours refactoring <code>useState<\/code> code, let\u2019s talk. We can review your current React state setup, recommend the right approach (whether that\u2019s <code>useReducer<\/code>, custom reducers, or Redux), and build the exact tools you need to make your app\u2019s state predictable and maintainable. Get in touch with us to start the conversation about how we can help your team use <code>useReducer<\/code> effectively.<\/p>\n<p><a href=\"https:\/\/www.hhfittings.com\/pipe-fittings\/pipe-bend\/\">Pipe Bend<\/a> References:<br \/>\nReact Documentation: useReducer Hook<br \/>\nRedux Documentation: Principles of Reducers<br \/>\nReact Beta Docs: State Management with useReducer<br \/>\nKent C. Dodds: How to use React\u2019s useReducer hook<br \/>\nReact TypeScript Cheat Sheet: useReducer with TypeScript<\/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 building React apps, you\u2019ve probably run into the moment where state &hellip; <a title=\"How to use useReducer in React?\" class=\"hm-read-more\" href=\"http:\/\/www.pixelmateindia.com\/blog\/2026\/11\/21\/how-to-use-usereducer-in-react-4a6e-6bdf93\/\"><span class=\"screen-reader-text\">How to use useReducer in React?<\/span>Read more<\/a><\/p>\n","protected":false},"author":431,"featured_media":879,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[842],"class_list":["post-879","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-industry","tag-reducer-48a8-6c24f3"],"_links":{"self":[{"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/posts\/879","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/users\/431"}],"replies":[{"embeddable":true,"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/comments?post=879"}],"version-history":[{"count":0,"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/posts\/879\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/posts\/879"}],"wp:attachment":[{"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/media?parent=879"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/categories?post=879"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.pixelmateindia.com\/blog\/wp-json\/wp\/v2\/tags?post=879"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}