1// Every rerender
2useEffect(() => {
3 console.log("I run everytime this component rerenders")
4});
5
6// onMount
7useEffect(() => {
8 console.log("I Only run once (When the component gets mounted)")
9}, []);
10
11// Condition based
12useEffect(() => {
13 console.log("I run everytime my condition is changed")
14}, [condition]);
15
16// Condition based with "clean up"
17useEffect(() => {
18 console.log("I run everytime my condition is changed")
19
20 return () => {
21 console.log("Use this return as a 'clean up tool' (this runs before the actual code)")
22 }
23}, [condition]);
1 useEffect(() => {
2 return () => {
3 console.log("cleaned up");
4 };
5 }, []);
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}
1useEffect(() => {
2 window.addEventListener('mousemove', () => {});
3
4 // returned function will be called on component unmount
5 return () => {
6 window.removeEventListener('mousemove', () => {})
7 }
8}, [])
1function FriendStatusWithCounter(props) {
2 const [count, setCount] = useState(0);
3 useEffect(() => { document.title = `You clicked ${count} times`;
4 });
5
6 const [isOnline, setIsOnline] = useState(null);
7 useEffect(() => { function handleStatusChange(status) {
8 setIsOnline(status.isOnline);
9 }
10
11 ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
12 return () => {
13 ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
14 };
15 });
16 // ...
17}