Saturday, November 16, 2024
Google search engine
HomeLanguagesExplain Reducers in Redux

Explain Reducers in Redux

In this article, we are going to learn about Reducer in Redux. A reducer is a pure function that determines changes to an application’s state. Reducer is one of the building blocks of Redux

As we have mentioned redux so before diving into the reducer function’s details, let’s know a little about what Redux is? Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application. 

USES OF REDUX: With the help of redux it is easy to manage state and data. As the complexity of our application increases. At the start, it is hard to understand but it really helps to build complex applications. In starting, it feels like a lot of work, but it is really helpful.

This was the small brief about redux. Now, we will discuss the reducer function.

REDUCER: In redux, the reducers are the pure functions that contain the logic and calculation that needed to be performed on the state. These functions accept the initial state of the state being used and the action type. It updates the state and responds with the new state. This updated state is sent back to the view components of the react to make the necessary changes. Basically, In short, we can say that Reducer’s work is to return the updated state and to also describe how the state changes.

Syntax: 

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

As we know, Reducers are pure functions hence they cannot do the following things:–. 

  • It cannot change or access any global variables.
  • It cannot make any API calls.
  • It cannot call any impure function in it like date or random

So, 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
}

Now, Let’s define the parameters of the reducer’s function i.e. state and action.

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.

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

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. For example, an educational application might have this action:

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

Now we know about state and action so let’s see how we can create a reducer function and update the state of the application. 

Steps to create a React-Redux Application:

Step 1: Initially, create a React app using the below-mentioned command:

npx create-react-app MyApp

Step 2: Once you create the folder with the appropriate folder name–MyApp–and go along with it with the following command:

cd MyApp

Step 3: Once you are done creating the ReactJS application, install redux and react-redux

npm install redux react-redux

Project Structure: It will look like the following:

Porject Structure

Example: In this 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.

App.jsx

Javascript




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;


index.js

Javascript




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


  • Filepath: src/reducers/func.js

Javascript




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;


  • Filepath: src/reducer/index.js

Javascript




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


store.js

Javascript




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


  • Filepath: src/index.js

Javascript




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")
);


Step to run the application: Open the terminal and type the following command.

npm start

Output:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments