useReducer

useReducer

Intermediatereact1 min read
use reducerreducer hookdispatchactionflux pattern

Definition

A React hook for managing complex state with a reducer function — an alternative to useState for multi-action state.

خطاف React لإدارة الحالة المعقدة بدالة reducer — بديل لـuseState لحالات متعددة الإجراءات.

Why It Matters

For multi-step forms, complex filter state, or any component where many useState hooks interact, useReducer gives cleaner and more predictable state transitions.

للنماذج متعددة الخطوات أو حالة الفلاتر المعقدة أو أي مكوّن تتفاعل فيه خطافات useState متعددة، يمنح useReducer انتقالات حالة أنظف وأكثر قابلية للتنبؤ.

Full Definition

useReducer accepts a reducer function and initial state, returning [state, dispatch]. The reducer receives `(state, action)` and returns the next state. Actions are objects describing what happened (typically `{ type: 'INCREMENT', payload: ... }`). Better than useState when multiple pieces of state depend on each other, or when the next state depends on complex logic. It's the same pattern Redux uses.
useReducer يقبل دالة reducer وحالة أولية، ويُعيد [state, dispatch]. يتلقى الـreducer `(state, action)` ويُعيد الحالة التالية. الإجراءات هي كائنات تصف ما حدث. أفضل من useState عندما تعتمد أجزاء متعددة من الحالة على بعضها.

Example Usage

const [state, dispatch] = useReducer(filterReducer, { search: '', category: '', difficulty: '' }); dispatch({ type: 'SET_SEARCH', payload: 'firebase' });

const [state, dispatch] = useReducer(filterReducer, { search: '', category: '', difficulty: '' }); dispatch({ type: 'SET_SEARCH', payload: 'firebase' });

Knowledge Graph

Avoid these mistakes when using useReducer:

1

Mutating state in the reducer — always return a new object

2

Overusing useReducer for simple state that useState handles fine

Sign in to unlock guided AI explanations from AI Teacher.

Generate a Prompt

Copy this prompt and use it directly with any AI model — no setup needed.

Ready-to-Use Prompt
Help me build a project using useReducer.

Explain:
1. What is useReducer and why it matters
2. The core architecture and required tools
3. Step-by-step implementation plan
4. Common mistakes to avoid: Mutating state in the reducer — always return a new object, Overusing useReducer for simple state that useState handles fine
5. Best practices and production tips

Official Resources