ReactJS useReducer Hook (original) (raw)

Last Updated : 12 Feb, 2025

The useReducer hook is an alternative to the useState hook that is preferred when you have complex state logic. It is useful when the state transitions depend on previous state values or when you need to handle actions that can update the state differently.

**Syntax

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

Implementing the useReducer hook

1. Basic Counter using useReducer

A common example of using useReducer is managing the state of a counter with actions to increment and decrement the value.

JavaScript `

import React, { useReducer } from 'react'; const counterReducer = (state, action) => { switch (action.type) { case 'INCREMENT': return { count: state.count + 1 }; case 'DECREMENT': return { count: state.count - 1 }; default: return state; } }; function Counter() { const [state, dispatch] = useReducer(counterReducer, { count: 0 }); return (

Count: {state.count}

<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement
); } export default Counter;

`

**Output

Animationkk

Counter app

**In this example

2. Managing Complex State with Multiple Actions

For more complex state management, you can use useReducer to handle actions that affect different parts of the state, such as managing a form or multiple values at once.

JavaScript `

import React, { useReducer } from 'react'; const initialState = { name: '', age: 0, submitted: false }; const formReducer = (state, action) => { switch (action.type) { case 'SET_NAME': return { ...state, name: action.payload }; case 'SET_AGE': return { ...state, age: action.payload }; case 'SUBMIT': return { ...state, submitted: true }; default: return state; } }; function Form() { const [state, dispatch] = useReducer(formReducer, initialState);

const handleSubmit = () => {
    dispatch({ type: 'SUBMIT' });
};
return (
    <div>
        <input
            type="text"
            value={state.name}
            onChange={(e) => dispatch({ type: 'SET_NAME', payload: e.target.value })}
            placeholder="Enter your name"
        />
        <input
            type="number"
            value={state.age}
            onChange={(e) => dispatch({ type: 'SET_AGE', payload: e.target.value })}
            placeholder="Enter your age"
        />
        <button onClick={handleSubmit}>Submit</button>
        {state.submitted && <p>Form Submitted!</p>}
    </div>
);

} export default Form;

`

**Output

**In this example

Interesting Things About the useReducer Hook

When to Use useReducer

**You should use useReducer when

useReducer vs useState

Both useReducer and useState manage state in React, but they serve different purposes:

Performance Considerations

While useReducer provides structure and clarity, it can be more complex and may add some overhead if used unnecessarily. Here are some performance considerations: