Definition of useReducer
✓ The useReducer hook in React is an alternative to Usestatedesigned for managing complex or structured state logic.
Syntax :
const [state, dispatch] = useReducer(reducer, Initial state)
✓ The useReducer have two arguments one is reducer function and another one is Initial value.
🔹 reducer: Custom state Processing function.
🔹 initialState: The initial value your state holds upon component mounting.
🔹 state: representing your current data.
🔹 dispatch: The unique trigger function used to call the Reducer function.
Example Code :
import { useReducer } from 'react'
import './App.css'
function App() {
function reducerFn(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 }
case "decrement":
return { count: state.count - 1 }
case "reset":
return { count: state.count + 1 }
}
}
const [state, dispatch] = useReducer(reducerFn, { count: 0 })
return (
<div>
<h1>count:{state.count}</h1>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
<button onClick={() => dispatch({ type: "decrement" })}>-</button>
<button onClick={() => dispatch({ type: "reset" })}>reset</button>
</div>
)
}
export default App;

Top comments (0)