SyntaxStudy
Sign Up
Home React Reference useReducer()

useReducer()

hook React 16.8

An alternative to useState for complex state logic. Similar to Redux pattern.

Syntax

const [state, dispatch] = useReducer(reducer, initialState)

Example

javascript
import { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
    switch (action.type) {
        case 'increment': return { count: state.count + 1 };
        case 'decrement': return { count: state.count - 1 };
        case 'reset':     return initialState;
        default: throw new Error('Unknown action');
    }
}

function Counter() {
    const [state, dispatch] = useReducer(reducer, initialState);
    return (
        <>
            <p>Count: {state.count}</p>
            <button onClick={() => dispatch({type:'increment'})}>+</button>
            <button onClick={() => dispatch({type:'decrement'})}>-</button>
        </>
    );
}