-
Notifications
You must be signed in to change notification settings - Fork 0
/
customHooks.js
99 lines (81 loc) · 2.51 KB
/
customHooks.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
const ReactX = (() => {
// let state; // can use only one state so make it array
// let state = []; // and adjust things
let hooks = [];// as we need for useEffect too so name it hooks
let index = 0; // to track
const useState = (initialValue) => {
// let state = initialValue;
const localIndex = index;
index++;
if (hooks[localIndex] === undefined) {
hooks[localIndex] = initialValue;
}
const setterFunction = (newValue) => {
hooks[localIndex] = newValue;
};
return [hooks[localIndex], setterFunction];
};
const resetIndex = () => {
index = 0;
};
const useEffect = (callback, dependencyArray) => {
let hasChanged = true;
let oldDependencies = hooks[index];
if (oldDependencies) {
hasChanged = false;
dependencyArray.forEach((dependency, index) => {
const oldDependency = oldDependencies[index];
const areTheSame = Object.is(oldDependency, dependency);
if (!areTheSame) {
hasChanged = true;
}
})
}
if (hasChanged) {
callback();
}
hooks[index] = dependencyArray;
index++;
}
const useMemo = (callback, dependencyArray) => {
const localIndex = index;
index++;
let hasChanged = true;
const oldDependencies = hooks[localIndex];
if (oldDependencies) {
hasChanged = dependencyArray.some((dependency, index) => {
return !Object.is(oldDependencies[index], dependency);
});
}
if (hasChanged) {
hooks[localIndex] = callback();
}
return hooks[localIndex];
};
return {
useState,
resetIndex,
useEffect,
useMemo
};
})();
const { useState, resetIndex, useEffect, useMemo } = ReactX;
const Component = () => {
const [count, setCount] = useState(1);
useEffect(() => {
console.log("hello");
}, [count])
console.log(count);
const memoizedValue = useMemo(() => {
console.log("Memoized value calculation");
return count * 2;
}, []);
console.log("Memoized Value:", memoizedValue);
if (count != 2) {
// this cause re-render so call component again
setCount(2);
}
};
Component();
resetIndex();
Component(); // but it returns 1 as each time its a different function so define hook state outside