Enterprise Verified
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.

The useReducer Hook is similar to useState, but is preferred when you have complex state logic involving multiple sub-values.

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

No questions yet. Be the first to start the discussion!
Enterprise Operations Suite

Streamline Employee Payroll & Attendance Operations

Eliminate manual spreadsheet errors. Integrate automated attendance tracking, EPF/ESI statutory calculations, and custom GST invoices.

Copied!

AI Learning Assistant

Ready to explain & guide

Hello! I am your MBS Digital AI Tutor. Ask me to explain concepts, review code, or suggest debugging steps.

Quick Starters:
AI Tutor is thinking...