1function App() {
2 const [count, setCount] = useState(0);
3
4 useEffect(() => {
5 longResolve().then(() => {
6 alert(count);
7 });
8 }, []);
9
10 return (
11 <div>
12 <button
13 onClick={() => {
14 setCount(count + 1);
15 }}
16 >
17 Count: {count}
18 </button>
19 </div>
20 );
21}
1import React, { useState, useEffect } from 'react';
2
3function Example() {
4 const [count, setCount] = useState(0);
5
6 // Similar to componentDidMount and componentDidUpdate:
7 useEffect(() => {
8 // Update the document title using the browser API
9 document.title = `You clicked ${count} times`;
10 });
11
12 return (
13 <div>
14 <p>You clicked {count} times</p>
15 <button onClick={() => setCount(count + 1)}>
16 Click me
17 </button>
18 </div>
19 );
20}
1import React, { useState, useEffect } from 'react';
2
3function Example() {
4 const [count, setCount] = useState(0);
5
6 // Similar to componentDidMount and componentDidUpdate:
7 useEffect(() => {
8 // Update the document title using the browser API
9 document.title = `You clicked ${count} times`;
10 });
11
12 return (
13 <div>
14 <p>You clicked {count} times</p>
15 <button onClick={() => setCount(count + 1)}>
16 Click me
17 </button>
18 </div>
19 );
20}
1import React, { useState, useEffect } from 'react';
2function Example() {
3 const [count, setCount] = useState(0);
4
5 useEffect(() => { document.title = `You clicked ${count} times`; });
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}
1//1.
2
3function App() {
4 const [isOn, setIsOn] = useState(false);
5
6 useEffect(() => {
7 const interval = setInterval(() => console.log('tick'), 1000);
8
9 return () => clearInterval(interval);
10 });
11}
12
13//2.
14
15function App() {
16 const [isOn, setIsOn] = useState(false);
17
18 useEffect(() => {
19 const interval = setInterval(() => console.log('tick'), 1000);
20
21 return () => clearInterval(interval);
22 }, []);
23}
24
25//3.
26
27function App() {
28 const [isOn, setIsOn] = useState(false);
29
30 useEffect(() => {
31 const interval = setInterval(() => console.log('tick'), 1000);
32
33 return () => clearInterval(interval);
34 }, [isOn]);
35}
36The first will run the effect on mount and whenever the state changes. The clean up will be called on state change and on unmount.
37
38The second will only run the effect once on mount and the clean up will only get called on unmount.
39
40The last will run the effect on mount and whenever the isOn state changes. The clean up will be called when isOn changes and on unmount.
41
42In your examples, the first and last examples will behave the same because the only state that will change is isOn. If the first example had more state, that effect would also refire if the other state were to change.
43
44I guess I should also add is that the order of things would be like: mount: -> run effect, state change: run clean up -> run effect, unmount -> run clean up.