-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.js
More file actions
86 lines (78 loc) · 2.08 KB
/
App.js
File metadata and controls
86 lines (78 loc) · 2.08 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import React, { useState, useEffect, useRef } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import { useInterval } from "./src/utils/useInterval";
function Counter() {
const [count, setCount] = useState(0);
const countRef = useRef(count);
countRef.current = count;
useEffect(() => {
// count = 0
const id = setInterval(() => {
if (countRef.current < 5) {
// ✅ This doesn't depend on `count` variable outside
setCount(c => c + 1); // ✅ This doesn't depend on `count` variable outside
} else {
setCount(0);
}
// setCount(prev => prev + 1);
}, 1000);
return () => clearInterval(id);
}, []); // ✅ Our effect doesn't use any variables in the component scope
return <Text style={styles.count}>{count}</Text>;
}
export default function App() {
const [count, setCount] = useState(0);
const [delay, setDelay] = useState(1000);
useInterval(() => {
// Your custom logic here
setCount(count + 1);
}, delay);
function handleDelayChange(text) {
if (text === "") {
setDelay(0);
} else {
setDelay(parseInt(text, 10));
}
}
return (
<View style={styles.container}>
<View flex={1} style={styles.subContainer}>
<Counter />
</View>
<View flex={2} style={styles.subContainer}>
<Text>Timer with custom hook</Text>
<Text>{count}</Text>
<TextInput
style={styles.textInput}
value={delay.toString()}
onChangeText={handleDelayChange}
/>
{/* <Button onPress={startInterval} title="Start" />
<Button onPress={clearInterval} title="Stop" /> */}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff"
},
subContainer: {
alignItems: "center",
justifyContent: "center"
},
textInput: {
width: 80,
height: 30,
borderColor: "#707070",
borderWidth: 1,
borderRadius: 5,
paddingLeft: 5,
marginTop: 5,
backgroundColor: "#fff"
},
count: {
fontSize: 30
}
});