Blog>
Snippets

Basic Counter with useReducer

Create a basic counter that increments and decrements a value using useReducer instead of useState for state management.
import React, { useReducer } from 'react';
Import the 'useReducer' hook from React.
// Action types for our counter
const INCREMENT = 'increment';
const DECREMENT = 'decrement';
Define the action types our counter reducer will handle.
// Reducer function that takes the current state and an action, and returns a new state
cost counterReducer = (state, action) => {
  switch (action.type) {
    case INCREMENT:
      return { count: state.count + 1 };
    case DECREMENT:
      return { count: state.count - 1 };
    default:
      return state;
  }
};
Create a reducer function with a switch statement handling increment and decrement actions.
// Counter component
function Counter() {
  const [state, dispatch] = useReducer(counterReducer, { count: 0 });

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: INCREMENT })}>+</button>
      <button onClick={() => dispatch({ type: DECREMENT })}>-</button>
    </div>
  );
}
Define the Counter component using the useReducer hook with our counterReducer and a default initial state. It also renders the count and buttons to dispatch increment and decrement actions.