Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created November 4, 2023 19:27
Show Gist options
  • Select an option

  • Save GalindoSVQ/81f132d23abdf552393579e4acca73b7 to your computer and use it in GitHub Desktop.

Select an option

Save GalindoSVQ/81f132d23abdf552393579e4acca73b7 to your computer and use it in GitHub Desktop.
import * as React from 'react';
export default function useCounter(startingValue = 0, options = {}) {
const { min, max } = options;
if (typeof min === 'number' && startingValue < min) {
throw new Error(
`Your starting value of ${startingValue} is less than your min of ${min}.`
);
}
if (typeof max === 'number' && startingValue > max) {
throw new Error(
`Your starting value of ${startingValue} is greater than your max of ${max}.`
);
}
const [count, setCount] = React.useState<number>(startingValue);
const increment = React.useCallback(() => {
setCount((c) => {
const newCountValue = c + 1;
if (newCountValue > max) {
return c;
}
return newCountValue;
});
}, [max]);
const decrement = React.useCallback(() => {
setCount((c) => {
const newCountValue = c - 1;
if (newCountValue < min) {
return c;
}
return newCountValue;
});
}, [min]);
const set = React.useCallback(
(nextState: number) => {
setCount((c) => {
if (nextState > max || nextState < min) {
return c;
}
return nextState;
});
},
[min, max]
);
const reset = () =>
React.useCallback(() => {
if (startingValue !== count) {
setCount(startingValue);
}
}, [startingValue]);
return [
count,
{
increment,
decrement,
set,
reset,
},
];
}
@GalindoSVQ

Copy link
Copy Markdown
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment