diff --git a/src/__stories__/useCounter.story.tsx b/src/__stories__/useCounter.story.tsx index 1c842e1092..a888a732b0 100644 --- a/src/__stories__/useCounter.story.tsx +++ b/src/__stories__/useCounter.story.tsx @@ -4,13 +4,18 @@ import {useCounter} from '..'; import ShowDocs from '../util/ShowDocs'; const Demo = () => { - const [value, inc, set] = useCounter(); + const [value, {inc, dec, get, set, reset}] = useCounter(5); return (
-
{value}
+
{value} is {get()}
+ + + + +
); }; diff --git a/src/useCounter.ts b/src/useCounter.ts index 975efed199..1a8dcf246a 100644 --- a/src/useCounter.ts +++ b/src/useCounter.ts @@ -1,12 +1,31 @@ -import {useState} from './react'; +import useGetSet from './useGetSet'; +import {useCallback} from './react'; -export type Increment = (inc?: number) => void; -export type Set = (value: number) => void; +export interface CounterActions { + inc: (delta?: number) => void; + dec: (delta?: number) => void; + get: () => number; + set: (value: number) => void; + reset: (value?: number) => void; +} -const useCounter = (initialValue: number = 0): [number, Increment, Set] => { - const [value, set] = useState(initialValue); +const useCounter = (initialValue: number = 0): [number, CounterActions] => { + const [get, set] = useGetSet(initialValue); + const inc = useCallback((delta: number = 1) => set(get() + delta), []); + const dec = useCallback((delta: number = 1) => inc(-delta), []); + const reset = useCallback((value: number = initialValue) => { + initialValue = value; + set(value); + }, []); + const actions = { + inc, + dec, + get, + set, + reset, + }; - return [value, (inc = 1) => set(value + inc), set]; + return [get(), actions]; }; export default useCounter; diff --git a/src/useGetSet.ts b/src/useGetSet.ts index 6e76bbb378..e9191c84ab 100644 --- a/src/useGetSet.ts +++ b/src/useGetSet.ts @@ -1,15 +1,14 @@ -import {useRef} from './react'; +import {useRef, useCallback} from './react'; import useUpdate from './useUpdate'; const useGetSet = (initialValue: T): [() => T, (value: T) => void] => { - const update = useUpdate(); let state = useRef(initialValue); - - const get = () => state.current; - const set = (value: T) => { + const update = useUpdate(); + const get = useCallback(() => state.current, []); + const set = useCallback((value: T) => { state.current = value; update(); - }; + }, []); return [get, set]; };