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 };
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);
For example, if our app starts with an empty contact list:
const initialState = { contacts: [] };
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' } };
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; } };
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; } };
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 } };
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)
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





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.

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

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.

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

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.

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

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

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...
