Created
November 4, 2023 19:27
-
-
Save GalindoSVQ/81f132d23abdf552393579e4acca73b7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | |
| }, | |
| ]; | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
stackblitz link: https://stackblitz.com/edit/vitejs-vite-4sfuam?file=src%2FuseCounter.ts