The useReducer hook is preferable to useState when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one (Redux-style).
React useReducer Hook
Manage complex state logic and transitions cleanly with action dispatches.
Key Takeaways: React useReducer Hook
Mastering React useReducer Hook helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
React useReducer Hook Code Example
Reactimport React, { useReducer } from "react";
function counterReducer(state, action) {
switch (action.type) {
case "increment": return { count: state.count + 1 };
case "decrement": return { count: state.count - 1 };
default: return state;
}
}
export default function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: "increment" })}>+</button>
</div>
);
}
Output
Interactive counter managed by reducer dispatch
Free sign-in required · Google login available
Finished this lesson?
Mark it complete to track your progress.
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services