1
- import { useState } from 'react'
1
+ import { memo , useCallback , useEffect , useMemo , useState } from 'react'
2
2
import reactLogo from './assets/react.svg'
3
3
import viteLogo from '/vite.svg'
4
4
import './App.css'
5
5
6
+ let appRenderingCount = 0
7
+
8
+ const MON_STYLE = { color : 'red' }
9
+
6
10
function App ( ) {
11
+ appRenderingCount ++
7
12
const [ count , setCount ] = useState ( 0 )
13
+ // const [count2, setCount2] = useState(0)
14
+ const [ date , setDate ] = useState ( new Date ( ) )
15
+
16
+
17
+
18
+ useEffect ( ( ) => {
19
+ setInterval ( ( ) => { setDate ( new Date ( ) ) } , 2000 )
20
+ } , [ ] ) ;
21
+
22
+ console . log ( `Rendering App #${ appRenderingCount } ...` )
23
+
24
+ const result = useMemo ( ( ) => {
25
+ console . log ( `re-calculating result...` )
26
+ return count + count2
27
+ } , [ count ] )
28
+ //
29
+ // const myCallback = useCallback(() => {
30
+ //
31
+ // }, [result])
8
32
9
33
return (
10
34
< >
@@ -18,9 +42,13 @@ function App() {
18
42
</ div >
19
43
< h1 > Vite + React ({ process . env . NODE_ENV } )</ h1 >
20
44
< div className = "card" >
21
- < button onClick = { ( ) => setCount ( ( count ) => count + 1 ) } >
22
- count is { count }
23
- </ button >
45
+ { 42 } < br />
46
+ { date . toISOString ( ) }
47
+ < MemoizedCounter style = { MON_STYLE } name = { 1 } count = { count } onClick = { ( ) => setCount ( count + 1 ) } />
48
+ < MemoizedCounter style = { MON_STYLE } name = { 2 } count = { count } onClick = { ( ) => setTimeout ( ( ) => {
49
+ setCount ( count + 1000 ) ;
50
+ } , 2000 ) } />
51
+ < MemoizedTodo />
24
52
< p >
25
53
Edit < code > src/App.tsx</ code > and save to test HMR
26
54
</ p >
@@ -32,4 +60,24 @@ function App() {
32
60
)
33
61
}
34
62
63
+ function Counter ( props : { name : number , style : Record < string , string > , count : number , onClick : ( ) => void } ) {
64
+ console . log ( `Rendering Counter #${ props . name } during #${ appRenderingCount } ` )
65
+ return (
66
+ < button onClick = { props . onClick } style = { props . style } >
67
+ count is { props . count }
68
+ </ button >
69
+ )
70
+ }
71
+
72
+ const MemoizedCounter = memo ( Counter , ( prev , next ) => Object . is ( prev . count , next . count ) )
73
+
74
+
75
+ function Toto ( ) {
76
+ console . log ( `Rendering Toto during #${ appRenderingCount } ` )
77
+ return ( < span onClick = { } > Toto</ span > )
78
+ }
79
+
80
+ const MemoizedTodo = memo ( Toto )
81
+
82
+
35
83
export default App
0 commit comments