![]() |
VOOZH | about |
Reducers in Redux are pure function that determines changes to an application’s state. Reducer is one of the building blocks of 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.
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.
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
}
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: []
}
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 geeksforgeeks',
'Web Development with GFG']
}
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
Output:
👁 Redux reducer example - output