How to use a Reducer with a stateful component in React?

May 21, 2025

Leave a message

Hey there! If you're into React and dealing with state management, you've probably heard about reducers. I'm a reducer supplier, and I've seen firsthand how powerful reducers can be when used with stateful components in React. In this blog, I'll walk you through how to use a reducer with a stateful component in React, and I'll also throw in some info about the reducers we supply.

What's a Reducer Anyway?

Before we dive into using a reducer with a stateful component, let's quickly go over what a reducer is. In the context of React, a reducer is a pure function that takes the current state and an action as arguments and returns a new state. It's a way to manage the state in a predictable and organized manner.

The basic structure of a reducer function looks like this:

function reducer(state, action) {
  switch (action.type) {
    case 'ACTION_TYPE_1':
      return { ...state, /* updated state properties */ };
    case 'ACTION_TYPE_2':
      return { ...state, /* updated state properties */ };
    default:
      return state;
  }
}

The state is the current state of your application, and the action is an object that describes what change you want to make to the state. The action typically has a type property that identifies the type of action and can also have additional data.

Stateful Components in React

In React, a stateful component is a component that manages its own state. You can create a stateful component using a class component or a functional component with the useState or useReducer hooks. For this blog, we'll focus on using the useReducer hook with a functional component.

Using a Reducer with a Stateful Component

Let's start by creating a simple example of using a reducer with a stateful component. Suppose we have a counter application where we can increment and decrement a counter value.

First, let's define our reducer function:

function counterReducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

Now, let's create our stateful component using the useReducer hook:

import React, { useReducer } from 'react';

function Counter() {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
    </div>
  );
}

export default Counter;

In this example, we import the useReducer hook from React. The useReducer hook takes two arguments: the reducer function (counterReducer) and the initial state ({ count: 0 }). It returns an array with two elements: the current state (state) and a dispatch function.

The dispatch function is used to send actions to the reducer. When we click the "Increment" or "Decrement" buttons, we call the dispatch function with an action object that has a type property. The reducer then processes the action and returns a new state.

Benefits of Using a Reducer with a Stateful Component

Using a reducer with a stateful component has several benefits:

  • Predictability: Reducers are pure functions, which means they always return the same output for the same input. This makes it easier to understand and debug your code.
  • Separation of Concerns: The reducer function is responsible for managing the state, while the component is responsible for rendering the UI. This separation makes your code more modular and easier to maintain.
  • Scalability: As your application grows, managing state with a reducer becomes more efficient and organized. You can easily add new actions and update the state logic without affecting other parts of your code.

Our Reducer Offerings

As a reducer supplier, we offer a wide range of high-quality reducers. Check out our High Quality Buttweld Concentric Reducer and Pipe Reducers. These reducers are designed to meet the highest industry standards and are suitable for various applications.

We also have the ASME B16.9 Buttweld Concentric Reducer, which complies with the ASME B16.9 standard. This standard ensures the quality and compatibility of the reducers, making them a reliable choice for your projects.

Handling Complex State with Reducers

In real-world applications, your state can be more complex than a simple counter. You might have multiple properties, nested objects, or arrays. Let's look at an example of handling a more complex state with a reducer.

Suppose we have a to-do list application where we can add, remove, and mark tasks as completed. Here's how we can define our reducer and stateful component:

function todoReducer(state, action) {
  switch (action.type) {
    case 'ADD_TASK':
      return {
        ...state,
        tasks: [...state.tasks, { id: Date.now(), text: action.payload, completed: false }]
      };
    case 'REMOVE_TASK':
      return {
        ...state,
        tasks: state.tasks.filter(task => task.id !== action.payload)
      };
    case 'TOGGLE_TASK':
      return {
        ...state,
        tasks: state.tasks.map(task =>
          task.id === action.payload ? { ...task, completed: !task.completed } : task
        )
      };
    default:
      return state;
  }
}

function TodoList() {
  const [state, dispatch] = useReducer(todoReducer, { tasks: [] });
  const [newTask, setNewTask] = React.useState('');

  const handleAddTask = () => {
    if (newTask.trim() !== '') {
      dispatch({ type: 'ADD_TASK', payload: newTask });
      setNewTask('');
    }
  };

  return (
    <div>
      <input
        type="text"
        value={newTask}
        onChange={(e) => setNewTask(e.target.value)}
        placeholder="Add a new task"
      />
      <button onClick={handleAddTask}>Add Task</button>
      <ul>
        {state.tasks.map(task => (
          <li key={task.id}>
            <span
              style={{ textDecoration: task.completed ? 'line-through' : 'none' }}
              onClick={() => dispatch({ type: 'TOGGLE_TASK', payload: task.id })}
            >
              {task.text}
            </span>
            <button onClick={() => dispatch({ type: 'REMOVE_TASK', payload: task.id })}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
}

export default TodoList;

In this example, our state is an object with a tasks property, which is an array of task objects. Each task object has an id, text, and completed property.

49 ASME B16.9 Stainless SteelCarbon Steel ASME Pipe Fitting Reducer (12-72 Sch10-Sch160) (4)49 ASME B16.9 Stainless SteelCarbon Steel ASME Pipe Fitting Reducer (12-72 Sch10-Sch160) (6)

The reducer handles three types of actions: ADD_TASK, REMOVE_TASK, and TOGGLE_TASK. The ADD_TASK action adds a new task to the tasks array, the REMOVE_TASK action removes a task from the array, and the TOGGLE_TASK action toggles the completed status of a task.

Contact Us for Reducer Procurement

If you're interested in our reducers or have any questions about using reducers in your React applications, feel free to reach out to us. We're here to help you find the right reducers for your needs and provide you with the best possible service. Whether you're working on a small project or a large-scale application, we have the expertise and products to support you.

References

  • React Documentation: https://reactjs.org/docs/hooks-reference.html#usereducer
  • Redux Documentation: https://redux.js.org/

Send Inquiry