useReducer

Pascual Vila
Frontend Instructor.
useReducer is a hook that is useful when a component's state is complex or depends on previous state values. It is a more robust alternative to useState, especially for handling more complex update logic.
Example of useReducer:
{`import React, { useReducer } from "react";
const counterReducer = (state, action) => {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
default:
return state;
}
};
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<h1>Counter: {state.count}</h1>
<button onClick={() => dispatch({ type: "increment" })}>Increment</button>
<button onClick={() => dispatch({ type: "decrement" })}>Decrement</button>
</div>
);
}
export default Counter;`}