-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhooks2.js
60 lines (48 loc) · 1.2 KB
/
hooks2.js
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
60
export function createHooks(callback) {
const stateContext = {
current: 0,
states: [],
};
const memoContext = {
current: 0,
memos: [],
};
function resetContext() {
stateContext.current = 0;
memoContext.current = 0;
}
let rafId;
const useState = (initState) => {
const { current, states } = stateContext;
stateContext.current += 1;
states[current] = states[current] ?? initState;
const setState = (newState) => {
if (newState === states[current]) return;
states[current] = newState;
cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(callback);
};
return [states[current], setState];
};
const useMemo = (fn, refs) => {
const { current, memos } = memoContext;
memoContext.current += 1;
const memo = memos[current];
const resetAndReturn = () => {
const value = fn();
memos[current] = {
value,
refs,
};
return value;
};
if (!memo) {
return resetAndReturn();
}
if (refs.length > 0 && memo.refs.find((v, k) => v !== refs[k])) {
return resetAndReturn();
}
return memo.value;
};
return { useState, useMemo, resetContext };
}