Skip to content

Instantly share code, notes, and snippets.

@anderjs
Created December 26, 2019 20:41
Show Gist options
  • Save anderjs/b60ad15632ffeafcc6d9e2dd94f5adf4 to your computer and use it in GitHub Desktop.
Save anderjs/b60ad15632ffeafcc6d9e2dd94f5adf4 to your computer and use it in GitHub Desktop.
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