-
Notifications
You must be signed in to change notification settings - Fork 0
/
useStateWithHistory.jsx
64 lines (42 loc) · 1.62 KB
/
useStateWithHistory.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/* بِسْمِ اللهِ الرَّحْمٰنِ الرَّحِيْمِ ﷺ */
import {useState,useRef, useCallback} from 'react';
export const useStateWithHistory = (defaultValue, {capacity = 10}) => {
let [value,setValue] = useState(defaultValue)
let historyRef = useRef([value])
let pointerRef = useRef(0)
const Set = useCallback( v => {
let resolveValue = typeof v === 'function'? v(value) : v
if (historyRef.current[pointerRef.current]!== resolveValue ) {
if (pointerRef.current < historyRef.current.length -1 ) {
// if any time historyref is not configured for pointerRef
historyRef.current.splice(pointerRef.current + 1)
}
historyRef.current.push(resolveValue)
while (historyRef.current.length > capacity) {
historyRef.current.shift()
}
pointerRef.current = historyRef.current.length -1
setValue(resolveValue)
}
}, [capacity, value])
const back = useCallback( () => {
if ( pointerRef.current <= 0 ) return
pointerRef.current--
setValue(history.current[pointerRef.current])
}, [])
const forward = useCallback(() => {
if(pointerRef.current >= historyRef.current.length -1) return
pointerRef.current++;
setValue(history.current[pointerRef.current])
},[])
const go = useCallback(index => {
if (index < 0 || index >= historyRef.current.length -1 ) return
pointerRef.current = index
setValue(history.current[pointerRef.current])
})
return [value, setValue, {
history : historyRef.current,
pointer : pointerRef.current,
Set, go, back, forward
} ]
}