What is a reducer function in javascript?

In the useReducer hook, the reducer is a pure function that takes the current state and an action and returns the next state. It handles the logic for updating the state based on the dispatched actions.

Here is an example of a reducer function:

function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error(); }
}

In this example, the reducer function takes the current state and an action, and returns a new state based on the action type. If the action type is 'increment', the reducer increments the count value in the state and returns the new state. If the action type is 'decrement', the reducer decrements the count value and returns the new state.

The useReducer hook takes the reducer function and an initial state as arguments and returns an array containing the current state and a dispatch function. The dispatch function sends actions to the reducer, which updates the state and re-renders the component with the new state.

Here is an example of how you might use useReducer in a React component:

import { useReducer } from 'react';
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
Count: {state.count}
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
</div> );
}

In this example, the Counter component uses useReducer to manage its state. The reducer function handles the logic for updating the state based on the actions that are dispatched, and the component uses the dispatch function to send actions to the reducer.

DCT Academy
A Full Stack web development training institute in Bangalore

Launch your GraphyLaunch your Graphy
100K+ creators trust Graphy to teach online
𝕏
Best MERN Full Stack Development Course | Bangalore | Offline | Online | 100% Placements | Training Institute | Front End Course | React JS Training | Online Course India 2024 Privacy policy Terms of use Contact us Refund policy