The useReducer Hook is similar to useState, but is preferred when you have complex state logic involving multiple sub-values.
React Frontend Framework
React Tutorial
Advertisement
Google AdSense Slot (LEADERBOARD)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Complex State
8 min read
•
Chapter 23 of 26
React useReducer
Manage complex state logic in React with the useReducer Hook, actions, and reducer functions.
Example
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body style="font-family:sans-serif;padding:20px;">
<div id="root"></div>
<script type="text/babel">
function reducer(state, action) {
switch (action.type) {
case "increment": return { count: state.count + 1 };
case "decrement": return { count: Math.max(0, state.count - 1) };
case "reset": return { count: 0 };
default: return state;
}
}
function Counter() {
const [state, dispatch] = React.useReducer(reducer, { count: 0 });
return (
<div>
<h3>Count: {state.count}</h3>
<button onClick={() => dispatch({ type: "increment" })}>+1</button>
<button onClick={() => dispatch({ type: "decrement" })} style={{margin: "0 6px"}}>-1</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")).render(<Counter />);
</script>
</body>
</html>
Try it Yourself >>
Opens live sandboxed code editor
Advertisement
Google AdSense Slot (IN-ARTICLE)
Automated High-CTR Ad Rail • Set Publisher ID in config/adsense.php
Community Q&A & Discussion
Verified
No questions yet. Be the first to start the discussion!