Create a counter component using useState and useReducer in React.

Understand how to build counters in React using both useState for simplicity and useReducer for structured state updates.

intermediateForms and inputsreactuseStateuseReducerstate management
Published: 10/26/2025
Updated: 10/26/2025

Question

Create a counter component using useState and useReducer in React.


Answer

Using useState (simple)

import { useState } from 'react';

function CounterState() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
      <button onClick={() => setCount(count - 1)}>-</button>
    </div>
  );
}

Using useReducer (structured)

import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      return state;
  }
}

function CounterReducer() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

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

✅ useReducer gives more control for complex state transitions — great for forms, multiple counters, or UI state management.

Real-World Example

  • Cart quantity in e-commerce
  • Step-based forms
  • Complex UI toggles

Quick Practice

Implement a ScoreCounter using useReducer with “reset” and “bonus +5” actions.

Summary

Use useState for simple updates, and useReducer when managing structured or multi-step state.

Related Videos
Watch these videos to learn more about this topic
Frequently Asked Questions

When should I use useReducer instead of useState?

Use useReducer when state logic is complex or involves multiple transitions.


Stay Updated

Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.