Introduction:
useReducer hook in react is used for state management. This hook is implemented in large projects where there is a need for managing multiple states.
The syntax for this hook is : useReducer(reducer,initialState)
This takes two arguments as input. The first argument is the reducer function and the second argument is an initial state and returns a pair of values [state, dispatch]
The reducer function is a pure function which means it generates only direct results. It takes two parameters current state and action and must return a value.
useReducer hook in Counter:
import React,{useReducer} from "react";
const initialState =0;
const reducer =(state,action)=>{
if(action.type==='increment')
return state+1;
if(action.type ==='decrement')
return state-1;
return state;
}
const UseReduce =()=>{
const [state,dispatch] = useReducer(reducer,initialState);
return(
<>
<div>
<p>{state}</p>
<div>
<button onClick={() => dispatch({type:'increment'})}>Increment</button>
<button onClick={() => dispatch({type:'decrement'})}>Decrement</button>
</div>
</div>
</>
)}
export default UseReduce;
Here the dispatch triggers the action method of the reducer function and sends the type of action as a parameter. Based on action type the operations are conditionally performed.