Open In App

Redux Reducers

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Reducers in Redux are pure function that determines changes to an application’s state. Reducer is one of the building blocks of Redux

What are Reducers in Redux ?

In Redux, reducers are pure functions that handle state logic, accepting the initial state and action type to update and return the state, facilitating changes in React view components.

(State,action) => newState

This was about the reducer syntax and its definition. Now we will discuss the term pure function that we have used before.

Pure function

A function is said to be pure if the return value is determined by its input values only and the return value is always the same for the same input values or arguments. A pure function has no side effects.

Pure Function Example:

Below is an example of a pure function:

const multiply= (x, y) => x * y;
multiply(5,3);

In the above example, the return value of the function is based on the inputs, if we pass 5 and 3 then we’d always get 15, as long as the value of the inputs is the same, the output will not get affected. 

Redux Reducer Syntax:

Here is an example of a reducer function that takes state and action as parameters.

const initialState = {};
const Reducer = (state = initialState, action) => {
// Write your code here
}

Redux Reducer Parameters:

  • Redux State
  • Redux Action

Redux State

The reducer function contains two parameters one of them is the state. The State is an object that holds some information that may change over the lifetime of the component. If the state of the object changes, the component has to re-render.

In redux, Updation of state happens in the reducer function. Basically reducer function returns a new state by performing an action on the initial state. Below, is an example of how we can declare the initial state of an application.

Redux State Syntax:

const INITIAL_STATE = {
userID: '',
name: '',
courses: []
}

Redux Actions

The second parameter of the reducer function is actions. Actions are JavaScript object that contains information. Actions are the only source of information for the store. The Actions object must include the type property and it can also contain the payload(data field in the actions) to describe the action.

Redux Action Syntax:

For example, an educational application might have this action:

{
type: 'CHANGE_USERNAME',
username: 'GEEKSFORGEEKS'
}
{
type: 'ADD_COURSE',
payload: ['Java with geeksforgeeks',
'Web Development with GFG']
}

Redux Reducer Working Example:

We have created two buttons one will increment the value by 2 and another will decrement the value by 2 but, if the value is 0, it will not get decremented we can only increment it. With Redux, we are managing the state state-managing

Javascript




// Filename - App.js
 
import React from 'react';
import './index.css';
import { useSelector, useDispatch } from 'react-redux';
import { incNum, decNum } from './actions/index';
function App() {
    const mystate = useSelector((state) => state.change);
    const dispatch = useDispatch();
    return (
        <>
            <h2>Increment/Decrement the number by 2,
                using Redux.</h2>
            <div className="app">
 
                <h1>{mystate}</h1>
                <button onClick={() => dispatch(incNum())}>
                    +</button>
                <button onClick={() => dispatch(decNum())}>
                    -</button>
            </div>
        </>
    );
}
export default App;


Javascript




//src/index.js
 
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App.jsx'
import store from './store';
import { Provider } from 'react-redux';
 
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>
    , document.getElementById("root")
);


Javascript




//index.js
 
export const incNum = () => {
    return { type: "INCREMENT" }
}
export const decNum = () => {
    return { type: "DECREMENT" }
}


Javascript




//reducers/func.js
const initialState = 0;
const change = (state = initialState, action) => {
    switch (action.type) {
        case "INCREMENT": return state + 2;
        case "DECREMENT":
            if (state == 0) {
                return state;
            }
            else {
                return state - 2;
            }
        default: return state;
    }
}
export default change;


Javascript




//reducer/index.js
 
import change from './func'
import { combineReducers } from 'redux';
 
const rootReducer = combineReducers({
    change
});
 
export default rootReducer;


Javascript




//store.js
 
import { createStore } from 'redux';
import rootReducer from './reducers/index';
const store = createStore(rootReducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ &&
    window.__REDUX_DEVTOOLS_EXTENSION__());
export default store;


Output:

Redux reducer example - output



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads