useReducer:
useReducer is a React Hook used to manage complex state logic in your components. It is often described as a more powerful alternative to useState, particularly when the next state depends on the previous one or when you have multiple related state values that need to change together.
Syntax:
const [state, dispatch] = useReducer(reducer, initialArg, init?)
Reference:
reducer: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types.
initialArg: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the next init argument
optional init: The initializer function that should return the initial state. If it’s not specified, the initial state is set to initialArg. Otherwise, the initial state is set to the result of calling init(initialArg)(TBD)
dispatch: The dispatch function returned by useReducer lets you update the state to a different value and trigger a re-render. You need to pass the action as the only argument to the dispatch function
state: It holds the initial value and changes the value accordingly when the dispatch function executes
Code:
import React from "react";
import { useReducer } from "react";
function Counter(){
function counterReducer(state,action){
switch (action.type) {
case "Increment" :
return {count : state.count + 1}
case "Decrement" :
return {count : state.count - 1}
case "Reset" :
return {count : 0}
}
}
const [state,dispatch] = useReducer(counterReducer,{count : 0})
return(
<>
<h1>{state.count}</h1>
<button onClick={()=>dispatch({type:"Increment"})}>Increment</button>
<button onClick={()=>dispatch({type:"Decrement"})}>Decrement</button>
<button onClick={()=>dispatch({type:"Reset"})}>Reset</button>
</>
)
}
export default Counter
Output:

Top comments (0)