1// Hooks let you build stateful and dynamic components
2
3import React, { useState } from 'react';
4function Example() {
5 // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
6 return (
7 <div>
8 <p>You clicked {count} times</p>
9 <button onClick={() => setCount(count + 1)}>
10 Click me
11 </button>
12 </div>
13 );
14}
1import React, { useState, useEffect } from "react";
2export default props => {
3 console.log("componentWillMount");
4 console.log("componentWillReceiveProps", props);
5 const [x, setX] = useState(0);
6 const [y, setY] = useState(0);
7 const [moveCount, setMoveCount] = useState(0);
8 const [cross, setCross] = useState(0);
9 const mouseMoveHandler = event => {
10 setX(event.clientX);
11 setY(event.clientY);
12 };
13 useEffect(() => {
14 console.log("componentDidMount");
15 document.addEventListener("mousemove", mouseMoveHandler);
16 return () => {
17 console.log("componentWillUnmount");
18 document.removeEventListener("mousemove", mouseMoveHandler);
19 };
20 }, []); // empty-array means don't watch for any updates
21 useEffect(
22 () => {
23 // if (componentDidUpdate & (x or y changed))
24 setMoveCount(moveCount + 1);
25 },
26 [x, y]
27 );
28useEffect(() => {
29 // if componentDidUpdate or componentDidMount
30 if (x === y) {
31 setCross(x);
32 }
33 });
34 return (
35 <div>
36 <p style={{ color: props.color }}>
37 Your mouse is at {x}, {y} position.
38 </p>
39 <p>Your mouse has moved {moveCount} times</p>
40 <p>
41 X and Y positions were last equal at {cross}, {cross}
42 </p>
43 </div>
44 );
45};
1import React, { useState } from 'react';
2function Example() {
3 // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
4 return (
5 <div>
6 <p>You clicked {count} times</p>
7 <button onClick={() => setCount(count + 1)}>
8 Click me
9 </button>
10 </div>
11 );
12}
1const App = () => {
2const [students , setStudents] = useState([]);
3
4 return (
5// put in the jsx code here
6 )
7}
1import React, { useState } from "react";
2
3function App() {
4
5 const [list, setList] = useState(" ");
6
7 const [items, updateOnClick] = useState([ ]);
8
9 function updateList(event) {
10 const valueEntered = event.target.value;
11 setList(valueEntered);
12 }
13
14 function updateClick(){
15 updateOnClick(list);
16 }
17 return (
18 <input onChange={updateList} type="text" value={list} />
19 <button onClick={updateClick}>
20 <span>Add</span>
21 </button>
22 <div>
23 <ul>
24 {items.map(item => <li>{item}</li>) }
25 </ul>
26 </div>);}
27export default App;