There are no items in your cart
Add More
Add More
Item Details | Price |
---|
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