-
-
Notifications
You must be signed in to change notification settings - Fork 967
Expand file tree
/
Copy pathReactHooksDemo.tsx
More file actions
69 lines (50 loc) · 1.57 KB
/
ReactHooksDemo.tsx
File metadata and controls
69 lines (50 loc) · 1.57 KB
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
import React, { useState, useEffect, useMemo, useRef, useCallback } from "react";
export default function ReactHooksDemo() {
// useState
const [count, setCount] = useState(0);
// useEffect
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
return () => clearInterval(interval);
}, []);
// useMemo
const expensiveCalculation = (num: number) => {
console.log("Calculating...");
return num * 1000;
};
const memoizedValue = useMemo(() => {
return expensiveCalculation(count);
}, [count]);
// useRef
const inputRef = useRef<HTMLInputElement>(null);
const focusInput = () => {
inputRef.current?.focus();
};
// useCallback
const resetCounter = useCallback(() => {
setCount(0);
}, []);
return (
<div style={{ padding: "20px", fontFamily: "sans-serif" }}>
<h2>React Hooks Demo</h2>
<hr />
<h3>useState Counter</h3>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
<button onClick={resetCounter}>Reset</button>
<hr />
<h3>useEffect Timer</h3>
<p>Timer running: {seconds} seconds</p>
<hr />
<h3>useMemo Expensive Calculation</h3>
<p>Memoized Value: {memoizedValue}</p>
<hr />
<h3>useRef Input Focus</h3>
<input ref={inputRef} placeholder="Click button to focus me" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}