Skip to main content
Home
Drupal life hacks

Main navigation

  • Drupal
  • React
  • WP
  • Contact
  • About
User account menu
  • Log in

Breadcrumb

  1. Home

Understanding Redux: Reducer Concept

By admin, 5 April, 2024

A reducer in Redux is a pure function that takes the previous state and an action, and returns the next state. Essentially, a reducer determines how your application's state changes in response to an action dispatched to the Redux store.

Key aspects of reducers in Redux:

1. Purity: Reducers should be pure functions, meaning they should not modify their arguments or have side effects. They should return a new state object rather than modifying the existing one.

2. Using switch: Typically, reducers use a switch statement to handle different action types. Each case inside the switch handles a specific action type and returns the corresponding state change.

Here's an example of a simple reducer in Redux:

const initialState = {
 count: 0
};
const counterReducer = (state = initialState, action) => {
 switch (action.type) {
   case 'INCREMENT':
     return { ...state, count: state.count + 1 };
   case 'DECREMENT':
     return { ...state, count: state.count - 1 };
   default:
     return state;
 }
};

In this example, counterReducer is a reducer that manages the state change of a counter based on the action type. It takes the previous state state and the action action, and returns a new state depending on the action type.

Tags

  • React

Comments

About text formats

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
Powered by Drupal