-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path16-custom-hooks.html
60 lines (50 loc) · 1.77 KB
/
16-custom-hooks.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>16-custom-hooks</title>
</head>
<body>
<div id="root"></div>
<!-- URL's changed for react libs. `React.useState not defined in [email protected]` -->
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.js"></script>
<script type="text/babel">
function useLocalStorageState(key, defaultValue = "") {
const [state, setState] = React.useState(
() => window.localStorage.getItem(key) || defaultValue
);
React.useEffect(() => {
window.localStorage.setItem(key, state);
}, [key, state]);
return [state, setState];
}
function Greeting() {
const [name, setName] = useLocalStorageState("name");
const handleChange = (event) => setName(event.target.value);
return (
<div>
<form>
<label htmlFor="name">Name: </label>
<input value={name} onChange={handleChange} id="name" />
</form>
{name ? <strong>Hello {name}</strong> : "Please type your name"}
</div>
);
}
function App() {
const [count, setCount] = React.useState(0);
return (
<>
<button onClick={() => setCount((c) => c + 1)}>{count}</button>
<Greeting />
</>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
</script>
</body>
</html>