MCPcopy
hub / github.com/streamich/react-use / useCounter

Function useCounter

src/useCounter.ts:13–97  ·  view source on GitHub ↗
(
  initialValue: IHookStateInitAction<number> = 0,
  max: number | null = null,
  min: number | null = null
)

Source from the content-addressed store, hash-verified

11}
12
13export default function useCounter(
14 initialValue: IHookStateInitAction<number> = 0,
15 max: number | null = null,
16 min: number | null = null
17): [number, CounterActions] {
18 let init = resolveHookState(initialValue);
19
20 typeof init !== 'number' &&
21 console.error('initialValue has to be a number, got ' + typeof initialValue);
22
23 if (typeof min === 'number') {
24 init = Math.max(init, min);
25 } else if (min !== null) {
26 console.error('min has to be a number, got ' + typeof min);
27 }
28
29 if (typeof max === 'number') {
30 init = Math.min(init, max);
31 } else if (max !== null) {
32 console.error('max has to be a number, got ' + typeof max);
33 }
34
35 const [get, setInternal] = useGetSet(init);
36
37 return [
38 get(),
39 useMemo(() => {
40 const set = (newState: IHookStateSetAction<number>) => {
41 const prevState = get();
42 let rState = resolveHookState(newState, prevState);
43
44 if (prevState !== rState) {
45 if (typeof min === 'number') {
46 rState = Math.max(rState, min);
47 }
48 if (typeof max === 'number') {
49 rState = Math.min(rState, max);
50 }
51
52 prevState !== rState && setInternal(rState);
53 }
54 };
55
56 return {
57 get,
58 set,
59 inc: (delta: IHookStateSetAction<number> = 1) => {
60 const rDelta = resolveHookState(delta, get());
61
62 if (typeof rDelta !== 'number') {
63 console.error(
64 'delta has to be a number or function returning a number, got ' + typeof rDelta
65 );
66 }
67
68 set((num: number) => num + rDelta);
69 },
70 dec: (delta: IHookStateSetAction<number> = 1) => {

Callers 10

DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
DemoFunction · 0.90
setUpFunction · 0.85

Calls 4

resolveHookStateFunction · 0.90
useGetSetFunction · 0.85
getFunction · 0.85
setFunction · 0.70

Tested by 1

setUpFunction · 0.68

Used in the wild real call sites across dependent graphs

searching dependent graphs…