Skip to content
Home Tutorials Roadmaps Courses
Log in Join free
Tutorials React useReducer Hook
React Intermediate FREE

useReducer Hook

Lesson 1 of 17 Intermediate Interactive

useReducer manages complex state logic with a reducer function.

Syntax

REACT
function reducer(state, action) {
    switch (action.type) {
        case 'increment': return { count: state.count + 1 };
        case 'decrement': return { count: state.count - 1 };
    }
}

const [state, dispatch] = useReducer(reducer, { count: 0 });
useReducer Hook
REACT
import { useReducer } from "react";

function reducer(state, action) {
    switch (action.type) {
        case "increment": return { count: state.count + 1 };
        case "decrement": return { count: state.count - 1 };
        case "reset": return { count: 0 };
        default: return state;
    }
}

function Counter() {
    const [state, dispatch] = useReducer(reducer, { count: 0 });

    return (
        <div>
            <p>Count: {state.count}</p>
            <button onClick={() => dispatch({ type: "increment" })}>+</button>
            <button onClick={() => dispatch({ type: "decrement" })}>-</button>
            <button onClick={() => dispatch({ type: "reset" })}>Reset</button>
        </div>
    );
}

Practice

1
Exercise

Practice this concept.

Answer
Write the code as shown above.

Quick Quiz

1

What did you learn?

This covers the basics.

Interview Questions

It is a fundamental React feature.