Created
March 23, 2020 16:55
-
-
Save anderjs/fcd05737998df3b746c345b29e6371c8 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 | |
})) | |
}, []) | |
const reset = useCallback(() => { | |
setState(prevState => ({ | |
...prevState, | |
value: 0 | |
})) | |
}, []) | |
const set = useCallback( | |
/** | |
* @param {number} value | |
*/ | |
value => { | |
setState(prevState => ({ | |
...prevState, | |
value: value | |
})) | |
}, [] | |
) | |
/** | |
* @alias ComputedProperty | |
* @description | |
* Assigns a memoized representation of fns. | |
*/ | |
const update = useMemo(() => ({ | |
increment, | |
decrement, | |
limit: | |
/** | |
* @param {number} value | |
*/ | |
(value) => { | |
setState(prevState => ({ | |
...prevState, | |
limit: value | |
})) | |
}, | |
reset, | |
set | |
}), [increment, decrement, reset, set]) | |
/** | |
* @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]) | |
const isZero = useMemo(() => { | |
return state.value === 0 | |
}, [state.value]) | |
return [state, update, isZero, shouldNext] | |
} | |
export default useCounter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment