Created
December 26, 2019 20:41
-
-
Save anderjs/b60ad15632ffeafcc6d9e2dd94f5adf4 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 { useState, useCallback, useMemo } from 'react' | |
/** | |
* | |
* @param {number} initialValue | |
* @param {number} limit | |
*/ | |
function useCounter(initialValue, limit) { | |
const [ state, setState ] = useState({ | |
value: initialValue, | |
limit: limit | |
}) | |
/** | |
* @description | |
* Updates the counter. | |
* @returns {void} | |
*/ | |
const increment = useCallback( | |
/** | |
* @param {number} increaseBy | |
*/ | |
(increaseBy = 1) => { | |
setState(prevState => ({ | |
...prevState, | |
value: prevState.value + increaseBy | |
})) | |
}, []) | |
/** | |
* @description | |
* Updates the counter. | |
* @returns {void} | |
*/ | |
const decrement = useCallback( | |
/** | |
* @param {number} decreaseBy | |
*/ | |
(decreaseBy = 1) => { | |
setState(prevState => ({ | |
...prevState, | |
value: prevState.value - decreaseBy | |
})) | |
}, []) | |
/** | |
* @alias ComputedProperty | |
* @description | |
* Assigns a memoized representation of fns. | |
*/ | |
const update = useMemo(() => ({ | |
increment, | |
decrement | |
}), [increment, decrement]) | |
/** | |
* @alias ComputedProperty | |
* @description | |
* Indicates if the value has exceed the limit or not. | |
*/ | |
const shouldNext = useMemo(() => { | |
return state.value <= state.limit | |
}, [state.value, state.limit]) | |
return [state, update, shouldNext] | |
} | |
export default useCounter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment