This repository has been archived by the owner on Nov 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RefHook.js
122 lines (104 loc) · 2.48 KB
/
RefHook.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import { useState, useRef, useEffect } from "react";
import VanillaTilt from "vanilla-tilt";
const NoReRender = () => {
const countRef = useRef(0);
const handleClick = () => {
countRef.current++;
};
return (
<>
<h1>Does Not Cause Re-renders</h1>
<h2>Render Count: {countRef.current}</h2>
<button onClick={handleClick}>Click me</button>
</>
);
};
const Stopwatch = () => {
const timerIdRef = useRef(0);
const [count, setCount] = useState(0);
const startHandler = () => {
if (timerIdRef.current) return;
timerIdRef.current = setInterval(() => setCount((c) => c + 1), 1000);
};
const stopHandler = () => {
clearInterval(timerIdRef.current);
timerIdRef.current = 0;
};
useEffect(() => {
return () => clearInterval(timerIdRef.current);
}, []);
return (
<div>
<div>Timer: {count}s</div>
<div>
<button onClick={startHandler}>Start</button>
<button onClick={stopHandler}>Stop</button>
</div>
</div>
);
};
const AccessDomElement = () => {
const inputElementRef = useRef();
const focusInput = () => {
inputElementRef.current.focus();
};
return (
<>
<input type="text" ref={inputElementRef} />
<button onClick={focusInput}>Focus Input</button>
</>
);
};
const Tilt = ({ children }) => {
const tiltRef = useRef();
useEffect(() => {
const { current: tiltNode } = tiltRef;
const vanillaTiltOptions = {
max: 25,
speed: 400,
glare: true,
"max-glare": 0.5,
};
VanillaTilt.init(tiltNode, vanillaTiltOptions);
return () => tiltNode.vanillaTilt.destroy();
}, []);
return (
<div ref={tiltRef} className="tilt-root">
<div className="tilt-child">{children}</div>
</div>
);
};
const TrackStateChange = () => {
const [inputValue, setInputValue] = useState("");
const previousInputValue = useRef("");
useEffect(() => {
previousInputValue.current = inputValue;
}, [inputValue]);
return (
<>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
/>
<h2>Current Value: {inputValue}</h2>
<h2>Previous Value: {previousInputValue.current}</h2>
</>
);
};
const RefHook = () => (
<>
<NoReRender />
<hr />
<Stopwatch />
<hr />
<AccessDomElement />
<hr />
<Tilt>
<div className="totally-centered">vanilla-tilt.js</div>
</Tilt>
<hr />
<TrackStateChange />
</>
);
export { RefHook };