DEV Community

PONVEL M
PONVEL M

Posted on

Understanding useReducer in React (With Simple Logic)

As React applications grow, managing complex state using useState becomes difficult. When state logic depends on multiple conditions or actions, React provides a better solution called useReducer.

πŸ”Ή What is useReducer?

useReducer is a React Hook used to manage complex state logic in a predictable way.

In simple words:

useReducer is an alternative to useState when state updates are complex or related.

πŸ”Ή When should you use useReducer?

Use useReducer when:

State depends on previous state

Multiple actions modify the same state

Logic becomes messy with many useState calls

❌ Too many useState

useState(count)
useState(error)
useState(loading)

βœ… One useReducer

useReducer(reducer, initialState)

πŸ”Ή Basic Syntax of useReducer
const [state, dispatch] = useReducer(reducer, initialState);

state β†’ current state

dispatch β†’ function to send actions

reducer β†’ function that updates state

πŸ”Ή Simple Example: Counter using useReducer
1️⃣ Reducer Function
function reducer(state, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
}

2️⃣ Component
import { useReducer } from "react";

const initialState = { count: 0 };

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

return (
<>

Count: {state.count}


dispatch({ type: "INCREMENT" })}>+
dispatch({ type: "DECREMENT" })}>-
</>
);
}

πŸ”Ή How useReducer Works (Logic)

Component dispatches an action

Reducer receives current state and action

Reducer returns a new state

React updates UI automatically

πŸ”Ή Why Reducer Must Be Pure?

A reducer:

❌ Should not modify state directly

❌ Should not call APIs

βœ… Should return new state only

This makes state changes predictable and debuggable.

Top comments (0)