React Easy technical 0 views 1 min read

How does `useReducer` works? Explain with an example

Peer-reviewed by HireXTech Technical Panel Updated for 2025/2026 hiring Editorial standards
Practise this track
Interviewer Expectations for this Question
01
Core Competency

Assesses fundamental understanding of React conventions, runtime behavior, and memory/performance considerations.

02
Evaluation Criteria

Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.

Comprehensive Model Answer Verified Solution

The useReducer hooks works similarly to Redux, where:

  • You define a reducer function to handle state transitions.
  • You dispatch actions to update the state.

Counter Example with Increment, Decrement, and Reset:

  1. Reducer function:

Define a counter reducer function that takes the current state and an action object with a type, and returns a new state based on that type.

         function counterReducer(state, action) {
            switch (action.type) {
              case 'increment':
                return { count: state.count + 1 };
              case 'decrement':
                return { count: state.count - 1 };
              case 'reset':
                return { count: 0 };
              default:
                return state;
            }
          }
         
  1. Using useReducer:

Invoke useReducer with above reducer function along with initial state. Thereafter, you can attach dispatch actions for respective button handlers.

      import React, { useReducer } from 'react';

        function Counter() {
          const initialState = { count: 0 };
          const [state, dispatch] = useReducer(counterReducer, initialState);

          return (
            <div style={{ textAlign: 'center' }}>
              <h2>Count: {state.count}</h2>
              <button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
              <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
              <button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
            </div>
          );
        }

      export default Counter;
      

Once the new state has been returned, React re-renders the component with the updated state.count.

Candidate Response Strategy & Interview Tips

  1. Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
  2. Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
  3. Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
  4. Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.
Related Topics & Skills
Spotted an error or have an alternative solution?