UseReducer in ReactJS

useReducer is a React Hook used to manage more complex state logic compared to useState. It’s especially useful when:

  • State depends on the previous state.
  • There are multiple sub-values in the state.
  • You want to centralize state logic (similar to Redux, but locally).

Basic Syntax

const [state, dispatch] = useReducer(reducer, initialState);
  • reducer: A function that takes state and action, and returns a new state.
  • initialState: The starting state value.
  • state: The current state.
  • dispatch: A function to send actions to the reducer.

Simple Example: Counter

import React, { 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 };
default:
throw new Error();
}
}

export default function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);

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

Why Use useReducer Instead of useState?

  • Better for complex state: When your state has multiple related values.
  • Predictable state transitions: Logic is centralized in one reducer function.
  • Scales well when actions grow (like Redux but for local component state).

When to Prefer useReducer

  • Forms with many fields and dynamic updates.
  • Components with lots of toggles, counts, or dependent states.
  • You want to mimic Redux’s pattern but without external libraries.

Leave a comment