All files / hooks/use-counter/src useCounter.ts

100% Statements 10/10
100% Branches 1/1
100% Functions 6/6
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65                                                                                                58x   58x 25x     58x 19x     58x 7x     58x    
import { useCallback, useState } from "react";
 
/**
 * useCounter return type
 */
export interface UseCounterReturn {
  /**
   * Current counter value
   */
  count: number;
  /**
   * Increment the counter by 1
   */
  increment: () => void;
  /**
   * Decrement the counter by 1
   */
  decrement: () => void;
  /**
   * Reset the counter back to its initial value
   */
  reset: () => void;
}
 
/**
 * A hook for managing counter state with increment, decrement, and reset.
 * Ideal for quantity selectors, pagination, and scoreboards.
 *
 * @param initialValue - Initial counter value (default: 0)
 * @returns Object containing the current count and control functions
 *
 * @example
 * ```tsx
 * function Counter() {
 *   const { count, increment, decrement, reset } = useCounter(0);
 *
 *   return (
 *     <div>
 *       <h2>Counter: {count}</h2>
 *       <button onClick={increment}>+ Increment</button>
 *       <button onClick={decrement}>- Decrement</button>
 *       <button onClick={reset}>Reset</button>
 *     </div>
 *   );
 * }
 * ```
 */
export function useCounter(initialValue: number = 0): UseCounterReturn {
  const [count, setCount] = useState(initialValue);
 
  const increment = useCallback(() => {
    setCount((prev) => prev + 1);
  }, []);
 
  const decrement = useCallback(() => {
    setCount((prev) => prev - 1);
  }, []);
 
  const reset = useCallback(() => {
    setCount(initialValue);
  }, [initialValue]);
 
  return { count, increment, decrement, reset };
}