Table of Contents
Understanding "State" in Redux
The state Parameter
The action Parameter
Updating State Immutably
Using the Spread Operator
The switch Statement
A Complete Example (without Redux)
Home Web Front-end CSS Tutorial Understanding How Reducers are Used in Redux

Understanding How Reducers are Used in Redux

Apr 15, 2025 am 10:08 AM

Understanding How Reducers are Used in Redux

Redux reducers are core functions that manage application state changes. They take the current state and an action as input, and return a new state reflecting the action's effect. This ensures state immutability, a key principle in Redux for predictable and consistent behavior.

Why Redux? Redux leverages reducers to centralize state management within a single "store," providing a structured approach to state updates.

This guide focuses on understanding and working with reducer functions. We'll explore how they update application state and their crucial role within state management frameworks like Redux.

Understanding "State" in Redux

State represents the application's data at any given moment. Changes to state are triggered by user interactions (clicks, form submissions) or external events (network requests). In Redux, all state modifications occur exclusively within reducer functions. The reducer uses the current state and an action object to calculate the next state.

Mathematically:

Current State Action = New State

A reducer function typically looks like this:

const contactReducer = (state = initialState, action) => {
  // State update logic
};
Copy after login

The initialState and action are defined by the application.

The state Parameter

The state parameter represents the application's current state. Initially, this is the initialState.

contactReducer(initialState, action);
Copy after login

For example, if our app starts with an empty contact list:

const initialState = { contacts: [] };
Copy after login

This initialState becomes the initial state parameter for the reducer.

The action Parameter

An action is an object with at least a type property indicating the type of state change. The payload property (optional) carries data needed for the update. For creating a new contact:

const action = {
  type: 'NEW_CONTACT',
  payload: {
    name: 'John Doe',
    location: 'Lagos, Nigeria',
    email: 'john.doe@example.com'
  }
};
Copy after login

action.type is essential; action.payload provides structured data.

Updating State Immutably

Directly modifying the state is forbidden. Use Object.assign() or the spread operator (...) to create a new state object.

Using Object.assign()

const contactReducer = (state, action) => {
  switch (action.type) {
    case 'NEW_CONTACT':
      return Object.assign({}, state, {
        contacts: [...state.contacts, action.payload]
      });
    default:
      return state;
  }
};
Copy after login

Object.assign({}, state, ...) creates a new object, copying state and adding/modifying properties. The empty object {} is crucial to avoid mutation.

Using the Spread Operator

Alternatively, the spread operator provides a more concise approach:

const contactReducer = (state, action) => {
  switch (action.type) {
    case 'NEW_CONTACT':
      return { ...state, contacts: [...state.contacts, action.payload] };
    default:
      return state;
  }
};
Copy after login

This cleanly adds the new contact to the existing contacts array without altering the original state.

The switch Statement

The switch statement handles different action.type values, directing the state update accordingly.

const contactReducer = (state, action) => {
  switch (action.type) {
    case 'NEW_CONTACT':
      // ... (add contact logic)
      break;
    case 'UPDATE_CONTACT':
      // ... (update contact logic)
      break;
    case 'DELETE_CONTACT':
      // ... (delete contact logic)
      break;
    default:
      return state; // Return unchanged state for unknown actions
  }
};
Copy after login

The default case is crucial for handling unknown actions, preventing unexpected state changes.

A Complete Example (without Redux)

This demonstrates a reducer function in React (without Redux), showcasing the core principles:

// ... (React component code)
const [state, setState] = useState(initialState);

const handleNewContact = (contact) => {
  const action = { type: 'NEW_CONTACT', payload: contact };
  setState(contactReducer(state, action));
};

// ... (rest of component code)
Copy after login

This example shows how a reducer function can be used independently of Redux to manage state updates. Extending this to handle UPDATE_CONTACT is a straightforward exercise.

For more advanced Redux reducer usage, consult the official Redux documentation.

The above is the detailed content of Understanding How Reducers are Used in Redux. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...

See all articles