Skip to content

Instantly share code, notes, and snippets.

@pierodev0
Last active March 3, 2025 20:38
Show Gist options
  • Save pierodev0/a392864b818138864913728bfada351b to your computer and use it in GitHub Desktop.
Save pierodev0/a392864b818138864913728bfada351b to your computer and use it in GitHub Desktop.
opcional min max
import { useState } from 'react';
type UseCounterConfig = {
min?: number;
max?: number;
};
type CounterActions = {
increment: () => void;
decrement: () => void;
set: (value: number) => void;
reset: () => void;
};
export function useCounter(
initialValue: number,
config: UseCounterConfig = {},
): [number, CounterActions] {
const [count, setCount] = useState(initialValue);
const { min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER } = config;
const increment = () => {
setCount((prevCount) => (prevCount + 1 > max ? max : prevCount + 1));
};
const decrement = () => {
setCount((prevCount) => (prevCount - 1 < min ? min : prevCount - 1));
};
const set = (value: number) => setCount(value);
const reset = () => setCount(initialValue);
return [
count,
{
increment,
decrement,
set,
reset,
},
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment