Skip to content

Commit 0733f54

Browse files
16 - React useEffect
1 parent 51dbdd0 commit 0733f54

File tree

1 file changed

+30
-18
lines changed

1 file changed

+30
-18
lines changed

index.js

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,43 @@
1-
import React, {useState} from 'react'
1+
import React, {useEffect, useState} from 'react'
22
import ReactDOM from 'react-dom'
33

44

5-
const BtnLabel = (props) =>{
5+
const Timer = (props) =>{
6+
const [count, setCount] = useState(-1)
7+
console.log(count, props)
8+
useEffect(()=>{
9+
// lookup to api service
10+
}, [])
611

7-
return <span> - {props.count} </span>
8-
}
12+
useEffect(()=>{
13+
// console.log("mounted")
14+
// setCount(count+1)
15+
let myTimer;
16+
if (count > 10) {
17+
myTimer = setTimeout(()=>{
18+
setCount(count + 1)
19+
}, 1000)
20+
}
21+
22+
return () => {
23+
clearTimeout(myTimer)
24+
}
25+
}, [count])
926

10-
const Btn = (props) =>{
11-
const [clickCount, setClickCount] = useState(0)
12-
console.log(props)
13-
const shouldRenderCount = props.renderCount === true ? true : false
14-
const renderCountLabel = shouldRenderCount === true ? <BtnLabel count={clickCount} /> : null
15-
const handleClick = (event) =>{
16-
// alert("btn in react")
17-
setClickCount(clickCount + 1)
27+
const handleClick = _ => {
28+
setCount(count + 1)
1829
}
19-
return <button onClick={handleClick} className={`class-${clickCount}`}>hello react btn {renderCountLabel}</button>
30+
31+
return <div>
32+
33+
<h1>Timer - {count}</h1>
34+
<button onClick={handleClick}>Reset</button>
35+
</div>
2036
}
2137

2238
const App = () => {
2339
return <div>Hello world again.
24-
25-
<p> <Btn renderCount /></p>
26-
<p> <Btn /></p>
27-
<p> <Btn /></p>
28-
<p> <Btn /></p>
40+
<Timer className='my-timer' />
2941
</div>
3042
}
3143

0 commit comments

Comments
 (0)