What is the dispatch function useReducer?

In the useReducer hook, the dispatch function is used to send actions to the reducer, which updates the state and re-renders the component with the new state.

The useReducer hook takes a reducer function and an initial state as arguments, and returns an array containing the current state and a dispatch function. You can use the dispatch function to send actions to the reducer by calling it with an action object as an argument.

Here is an example of how you might use the dispatch function in a React component:

import { useReducer } from 'react';
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();
} }

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 dispatched actions. The component uses the dispatch function to send actions to the reducer when the buttons are clicked. When an action is dispatched, the reducer updates the state and the component re-renders with the new state.

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