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};
1function ExampleWithManyStates() {
2 // Declare multiple state variables!
3 const [age, setAge] = useState(42);
4 const [fruit, setFruit] = useState('banana');
5 const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
6 // ...
7}
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}
1useEffect(() => {
2 document.title = `You clicked ${count} times`;
3}, [count]); // Only re-run the effect if count changes