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: 'w3wiki'
}
{
type: 'ADD_COURSE',
payload: ['Java with w3wiki',
'Web Development with GFG']
}

Redux Reducers

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

Table of Content

  • What are Reducers in Redux ?
  • Pure function
  • Redux Reducer Working Example

Similar Reads

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

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

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