QA
Intermediate LevelReact JS & React 19

When should you use useReducer instead of useState for state management?

❓ Interview Prompt: Explain `useReducer`, reducer functions `(state, action) => newState`, state machine logic, dispatching actions, and complex state objects.

'useReducer' is an alternative to 'useState' ideal for managing complex state logic:

When to prefer 'useReducer':

1
State consists of multiple sub-values or nested objects.
2
The next state depends on intricate calculations involving the previous state.
3
Multiple event handlers trigger the same set of state transformations.
4
Enables Redux-like predictable state machine transitions via 'dispatch({ type: 'ACTION', payload })'.

Code Implementation Example

jsx
const initialState = { count: 0, step: 1 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment': return { ...state, count: state.count + state.step };
    case 'set_step': return { ...state, step: action.payload };
    default: throw new Error('Unknown action');
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);
  return <button onClick={() => dispatch({ type: 'increment' })}>{state.count}</button>;
}
💡Managing complex multi-field state using useReducer and action dispatching.
🎯 Interview Key Takeaway

Use useReducer when component state logic involves complex objects or multiple interdependent state transitions.

#useReducer#Hooks#Reducers#Intermediate
Back to all React JS & React 19 Questions→

More React JS & React 19 Interview Questions

Beginner LevelReact JS & React 19

What is JSX and how does it work under the hood?

Beginner LevelReact JS & React 19

What is the difference between props and state in React?

Beginner LevelReact JS & React 19

How does the useState hook work and what is functional updater syntax?